IAMTFRMZA commited on
Commit
2ed3eb2
·
verified ·
1 Parent(s): c273ee5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -35
app.py CHANGED
@@ -63,13 +63,13 @@ tab1, tab2 = st.tabs(["💬 Chat Assistant", "🖼️ Visual Reference Search"])
63
 
64
  # ------------------ Tab 1: Chat Assistant ------------------
65
  with tab1:
 
66
  with st.sidebar:
67
  st.header("🧪 Pathology Tools")
 
68
  if st.button("🧹 Clear Chat"):
69
- st.session_state.messages = []
70
- st.session_state.thread_id = None
71
- st.session_state.image_urls = []
72
- st.session_state.pending_prompt = None
73
  st.rerun()
74
 
75
  show_image = st.toggle("📸 Show Images", value=True)
@@ -81,16 +81,15 @@ with tab1:
81
  if section:
82
  st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
83
 
84
- actions = [
85
  "Select an action...",
86
  "List histological features of inflammation",
87
  "Summarize features of carcinoma",
88
  "List muscle types and features",
89
  "Extract diagnostic markers",
90
  "Summarize embryology stages"
91
- ]
92
- action = st.selectbox("Common Pathology Queries", actions)
93
- if action != actions[0]:
94
  st.session_state.pending_prompt = action
95
 
96
  chat_col, image_col = st.columns([2, 1])
@@ -98,17 +97,19 @@ with tab1:
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
  if user_input:
102
  st.session_state.messages.append({"role": "user", "content": user_input})
103
  elif st.session_state.pending_prompt:
104
  st.session_state.messages.append({"role": "user", "content": st.session_state.pending_prompt})
105
  st.session_state.pending_prompt = None
106
 
 
107
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
108
  try:
109
- if st.session_state.thread_id is None:
110
- thread = client.beta.threads.create()
111
- st.session_state.thread_id = thread.id
112
 
113
  client.beta.threads.messages.create(
114
  thread_id=st.session_state.thread_id,
@@ -129,39 +130,39 @@ with tab1:
129
  time.sleep(1)
130
 
131
  if status.status == "completed":
132
- messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
133
- for m in reversed(messages.data):
134
  if m.role == "assistant":
135
  reply = m.content[0].text.value.strip()
136
- is_duplicate = any(
137
- reply in msg["content"] or msg["content"] in reply
138
- for msg in st.session_state.messages if msg["role"] == "assistant"
139
- )
140
- if not is_duplicate:
141
  st.session_state.messages.append({"role": "assistant", "content": reply})
142
- image_matches = re.findall(
 
 
143
  r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n"]+\.png',
144
  reply
145
  )
146
- st.session_state.image_urls = image_matches
147
  break
148
  else:
149
- st.error("❌ Assistant failed to respond.")
150
  st.rerun()
151
  except Exception as e:
152
  st.error(f"❌ Error: {e}")
153
 
 
154
  for msg in st.session_state.messages:
155
  with st.chat_message(msg["role"]):
156
  st.markdown(msg["content"], unsafe_allow_html=True)
157
 
158
- # 🧠 Follow-up Suggestions
159
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant":
160
- latest_reply = st.session_state.messages[-1]["content"]
161
- match = re.search(r"Some Possible Questions:\s*(.*?)(?=\n#{2,}|\\Z)", latest_reply, re.DOTALL)
162
- if match:
163
- block = match.group(1)
164
- questions = [line.strip(" -•") for line in block.splitlines() if line.strip().startswith(("-", "•"))]
165
  if questions:
166
  st.markdown("#### 💡 Follow-Up Suggestions")
167
  for q in questions:
@@ -171,16 +172,13 @@ with tab1:
171
 
172
  with image_col:
173
  if show_image and st.session_state.image_urls:
174
- st.markdown("### 🖼️ Image(s)")
175
- for raw_url in st.session_state.image_urls:
176
  try:
177
- r = requests.get(raw_url, timeout=5)
178
- r.raise_for_status()
179
- img = Image.open(BytesIO(r.content))
180
- st.image(img, caption=f"📷 {raw_url.split('/')[-1]}", use_container_width=True)
181
  except Exception:
182
- continue
183
-
184
 
185
  # ------------------ Tab 2: Visual Reference Search ------------------
186
  with tab2:
 
63
 
64
  # ------------------ Tab 1: Chat Assistant ------------------
65
  with tab1:
66
+ # Sidebar
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)
 
81
  if section:
82
  st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
83
 
84
+ action = st.selectbox("Common Pathology Queries", [
85
  "Select an action...",
86
  "List histological features of inflammation",
87
  "Summarize features of carcinoma",
88
  "List muscle types and features",
89
  "Extract diagnostic markers",
90
  "Summarize embryology stages"
91
+ ])
92
+ if action != "Select an action...":
 
93
  st.session_state.pending_prompt = action
94
 
95
  chat_col, image_col = st.columns([2, 1])
 
97
  with chat_col:
98
  st.markdown("### 💬 Ask a Pathology-Specific Question")
99
  user_input = st.chat_input("Example: What are features of squamous cell carcinoma?")
100
+
101
+ # Append input or pending prompt
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
+ # Trigger assistant run
109
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
110
  try:
111
+ if not st.session_state.thread_id:
112
+ st.session_state.thread_id = client.beta.threads.create().id
 
113
 
114
  client.beta.threads.messages.create(
115
  thread_id=st.session_state.thread_id,
 
130
  time.sleep(1)
131
 
132
  if status.status == "completed":
133
+ responses = client.beta.threads.messages.list(thread_id=st.session_state.thread_id).data
134
+ for m in reversed(responses):
135
  if m.role == "assistant":
136
  reply = m.content[0].text.value.strip()
137
+
138
+ # De-dupe reply
139
+ if not any(reply in msg["content"] or msg["content"] in reply
140
+ for msg in st.session_state.messages if msg["role"] == "assistant"):
 
141
  st.session_state.messages.append({"role": "assistant", "content": reply})
142
+
143
+ # Image detection
144
+ images = re.findall(
145
  r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n"]+\.png',
146
  reply
147
  )
148
+ st.session_state.image_urls = images
149
  break
150
  else:
151
+ st.error("❌ Assistant failed to complete.")
152
  st.rerun()
153
  except Exception as e:
154
  st.error(f"❌ Error: {e}")
155
 
156
+ # Display conversation
157
  for msg in st.session_state.messages:
158
  with st.chat_message(msg["role"]):
159
  st.markdown(msg["content"], unsafe_allow_html=True)
160
 
161
+ # Optional follow-ups
162
  if st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant":
163
+ last = st.session_state.messages[-1]["content"]
164
+ if "Some Possible Questions:" in last:
165
+ questions = re.findall(r"[-•]\s*(.*)", last)
 
 
166
  if questions:
167
  st.markdown("#### 💡 Follow-Up Suggestions")
168
  for q in questions:
 
172
 
173
  with image_col:
174
  if show_image and st.session_state.image_urls:
175
+ st.markdown("### 🖼️ Images")
176
+ for url in st.session_state.image_urls:
177
  try:
178
+ img = Image.open(BytesIO(requests.get(url, timeout=5).content))
179
+ st.image(img, caption=url.split("/")[-1], use_container_width=True)
 
 
180
  except Exception:
181
+ st.warning(f"⚠️ Failed to load image: {url}")
 
182
 
183
  # ------------------ Tab 2: Visual Reference Search ------------------
184
  with tab2: