IAMTFRMZA commited on
Commit
ce1ad36
Β·
verified Β·
1 Parent(s): 279de0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -18
app.py CHANGED
@@ -29,24 +29,28 @@ def login():
29
 
30
  if "authenticated" not in st.session_state:
31
  st.session_state.authenticated = False
 
32
  if not st.session_state.authenticated:
33
  login()
34
  st.stop()
35
 
36
- # ------------------ Configuration ------------------
37
  st.set_page_config(page_title="AI Pathology Assistant", layout="wide", initial_sidebar_state="collapsed")
38
  st.title("🧬 AI Pathology Assistant")
39
  st.caption("AI-powered exploration of pathology, anatomy, and histology documents via OCR + GPT")
40
 
 
41
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
42
  if not OPENAI_API_KEY:
43
  st.error("❌ Missing OPENAI_API_KEY environment variable.")
44
  st.stop()
45
 
46
  client = OpenAI(api_key=OPENAI_API_KEY)
47
- ASSISTANT_ID = "asst_jXDSjCG8LI4HEaFEcjFVq8KB"
48
 
49
- # ------------------ State Setup ------------------
 
 
 
50
  if "messages" not in st.session_state:
51
  st.session_state.messages = []
52
  if "thread_id" not in st.session_state:
@@ -66,7 +70,7 @@ with st.sidebar:
66
  st.session_state.pending_prompt = None
67
  st.rerun()
68
 
69
- show_image = st.toggle("πŸ“Έ Show Images", value=True)
70
  keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
71
  if st.button("πŸ”Ž Search") and keyword:
72
  st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
@@ -87,7 +91,7 @@ with st.sidebar:
87
  if action != actions[0]:
88
  st.session_state.pending_prompt = action
89
 
90
- # ------------------ Chat UI ------------------
91
  chat_col, image_col = st.columns([2, 1])
92
 
93
  with chat_col:
@@ -127,20 +131,15 @@ with chat_col:
127
  messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
128
  for m in reversed(messages.data):
129
  if m.role == "assistant":
130
- raw_reply = m.content[0].text.value
 
131
 
 
132
  image_matches = re.findall(
133
- r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^"]+?\.png',
134
- raw_reply
135
  )
136
  st.session_state.image_urls = image_matches
137
-
138
- reply_cleaned = re.sub(
139
- r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^"]+?\.png',
140
- '[Image reference available in Slide Previews β†’]',
141
- raw_reply
142
- )
143
- st.session_state.messages.append({"role": "assistant", "content": reply_cleaned})
144
  break
145
  else:
146
  st.error("❌ Assistant failed to respond.")
@@ -152,19 +151,25 @@ with chat_col:
152
  with st.chat_message(msg["role"]):
153
  st.markdown(msg["content"], unsafe_allow_html=True)
154
 
155
- # ------------------ Image Display (Vertical Stack) ------------------
156
  with image_col:
157
  if show_image and st.session_state.image_urls:
158
- st.markdown("### πŸ–ΌοΈ Image(s)")
159
  for raw_url in st.session_state.image_urls:
160
  try:
 
 
 
161
  _, raw_path = raw_url.split("githubusercontent.com/", 1)
162
  segments = raw_path.strip().split("/")
163
  encoded_segments = [quote(seg) for seg in segments]
164
  encoded_url = "https://raw.githubusercontent.com/" + "/".join(encoded_segments)
 
 
165
  r = requests.get(encoded_url)
166
  r.raise_for_status()
167
  img = Image.open(BytesIO(r.content))
168
  st.image(img, caption=f"πŸ“· {encoded_segments[-1]}", use_container_width=True)
 
169
  except Exception as e:
170
- st.error(f"❌ Failed to load image: {e}")
 
29
 
30
  if "authenticated" not in st.session_state:
31
  st.session_state.authenticated = False
32
+
33
  if not st.session_state.authenticated:
34
  login()
35
  st.stop()
36
 
37
+ # ------------------ App Configuration ------------------
38
  st.set_page_config(page_title="AI Pathology Assistant", layout="wide", initial_sidebar_state="collapsed")
39
  st.title("🧬 AI Pathology Assistant")
40
  st.caption("AI-powered exploration of pathology, anatomy, and histology documents via OCR + GPT")
41
 
42
+ # ------------------ Load OpenAI API Key ------------------
43
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
44
  if not OPENAI_API_KEY:
45
  st.error("❌ Missing OPENAI_API_KEY environment variable.")
46
  st.stop()
47
 
48
  client = OpenAI(api_key=OPENAI_API_KEY)
 
49
 
50
+ # ------------------ Assistant Configuration ------------------
51
+ ASSISTANT_ID = "asst_jXDSjCG8LI4HEaFEcjFVq8KB" # Replace with your actual assistant ID
52
+
53
+ # ------------------ Session State ------------------
54
  if "messages" not in st.session_state:
55
  st.session_state.messages = []
56
  if "thread_id" not in st.session_state:
 
70
  st.session_state.pending_prompt = None
71
  st.rerun()
72
 
73
+ show_image = st.toggle("πŸ“Έ Show Slide Images", value=True)
74
  keyword = st.text_input("Keyword Search", placeholder="e.g. mitosis, carcinoma")
75
  if st.button("πŸ”Ž Search") and keyword:
76
  st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
 
91
  if action != actions[0]:
92
  st.session_state.pending_prompt = action
93
 
94
+ # ------------------ Main Chat UI ------------------
95
  chat_col, image_col = st.columns([2, 1])
96
 
97
  with chat_col:
 
131
  messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
132
  for m in reversed(messages.data):
133
  if m.role == "assistant":
134
+ reply = m.content[0].text.value
135
+ st.session_state.messages.append({"role": "assistant", "content": reply})
136
 
137
+ # βœ… Extract GitHub raw image URLs
138
  image_matches = re.findall(
139
+ r'https://raw\.githubusercontent\.com/AndrewLORTech/witspathologai/main/[^\s\n]+\.png',
140
+ reply
141
  )
142
  st.session_state.image_urls = image_matches
 
 
 
 
 
 
 
143
  break
144
  else:
145
  st.error("❌ Assistant failed to respond.")
 
151
  with st.chat_message(msg["role"]):
152
  st.markdown(msg["content"], unsafe_allow_html=True)
153
 
154
+ # ------------------ Image Display with Encoding Fix ------------------
155
  with image_col:
156
  if show_image and st.session_state.image_urls:
157
+ st.markdown("### πŸ–ΌοΈ Slide Previews")
158
  for raw_url in st.session_state.image_urls:
159
  try:
160
+ # Extract everything after the domain and encode each path segment
161
+ if "githubusercontent.com" not in raw_url:
162
+ continue
163
  _, raw_path = raw_url.split("githubusercontent.com/", 1)
164
  segments = raw_path.strip().split("/")
165
  encoded_segments = [quote(seg) for seg in segments]
166
  encoded_url = "https://raw.githubusercontent.com/" + "/".join(encoded_segments)
167
+
168
+ # Load and display
169
  r = requests.get(encoded_url)
170
  r.raise_for_status()
171
  img = Image.open(BytesIO(r.content))
172
  st.image(img, caption=f"πŸ“· {encoded_segments[-1]}", use_container_width=True)
173
+
174
  except Exception as e:
175
+ st.error(f"❌ Failed to load image from {raw_url}: {e}")