Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +81 -81
src/streamlit_app.py
CHANGED
@@ -2,7 +2,7 @@
|
|
2 |
# ✅ Cache-Safe Multimodal App
|
3 |
# ================================
|
4 |
|
5 |
-
import os
|
6 |
|
7 |
# ====== Force all cache dirs to /tmp (writable in most environments) ======
|
8 |
CACHE_BASE = "/tmp/cache"
|
@@ -13,6 +13,10 @@ os.environ["HF_DATASETS_CACHE"] = f"{CACHE_BASE}/hf_datasets"
|
|
13 |
os.environ["TORCH_HOME"] = f"{CACHE_BASE}/torch"
|
14 |
os.environ["STREAMLIT_CACHE_DIR"] = f"{CACHE_BASE}/streamlit_cache"
|
15 |
os.environ["STREAMLIT_STATIC_DIR"] = f"{CACHE_BASE}/streamlit_static"
|
|
|
|
|
|
|
|
|
16 |
|
17 |
# Create the directories before imports
|
18 |
for path in os.environ.values():
|
@@ -26,37 +30,30 @@ from sentence_transformers import SentenceTransformer, util
|
|
26 |
from transformers import CLIPProcessor, CLIPModel
|
27 |
from datasets import load_dataset, get_dataset_split_names
|
28 |
from PIL import Image
|
29 |
-
import
|
30 |
import comet_llm
|
31 |
from opik import track
|
32 |
|
33 |
-
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
|
34 |
-
os.environ["STREAMLIT_CACHE_DIR"] = f"{CACHE_BASE}/streamlit_cache"
|
35 |
-
os.environ["STREAMLIT_STATIC_DIR"] = f"{CACHE_BASE}/streamlit_static"
|
36 |
-
|
37 |
-
os.makedirs("/tmp/.streamlit", exist_ok=True)
|
38 |
-
|
39 |
-
|
40 |
# ========== 🔑 API Key ==========
|
41 |
-
|
42 |
os.environ["OPIK_API_KEY"] = os.getenv("OPIK_API_KEY")
|
43 |
os.environ["OPIK_WORKSPACE"] = os.getenv("OPIK_WORKSPACE")
|
44 |
# ========== 📥 Load Models ==========
|
45 |
@st.cache_resource(show_spinner=False)
|
46 |
def load_models():
|
47 |
-
|
48 |
"openai/clip-vit-base-patch32",
|
49 |
cache_dir=os.environ["TRANSFORMERS_CACHE"]
|
50 |
)
|
51 |
-
|
52 |
"openai/clip-vit-base-patch32",
|
53 |
cache_dir=os.environ["TRANSFORMERS_CACHE"]
|
54 |
)
|
55 |
-
|
56 |
"all-MiniLM-L6-v2",
|
57 |
cache_folder=os.environ["SENTENCE_TRANSFORMERS_HOME"]
|
58 |
)
|
59 |
-
return
|
60 |
|
61 |
clip_model, clip_processor, text_model = load_models()
|
62 |
|
@@ -72,10 +69,24 @@ def load_medical_data():
|
|
72 |
)
|
73 |
return dataset
|
74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
data = load_medical_data()
|
|
|
76 |
|
77 |
-
|
78 |
-
client = OpenAI(api_key=openai.api_key)
|
79 |
# Temporary debug display
|
80 |
#st.write("Dataset columns:", data.features.keys())
|
81 |
|
@@ -102,17 +113,37 @@ combined_texts = prepare_combined_texts(data)
|
|
102 |
def embed_dataset_texts(_texts):
|
103 |
return text_model.encode(_texts, convert_to_tensor=True)
|
104 |
|
105 |
-
def embed_query_text(
|
106 |
-
return text_model.encode([
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
|
108 |
# Pick which text column to use
|
109 |
TEXT_COLUMN = "complaints" # or "general_complaint", depending on your needs
|
110 |
|
111 |
# ========== 🧑⚕️ App UI ==========
|
112 |
-
st.title("🩺
|
113 |
|
114 |
query = st.text_input("Enter your medical question or symptom description:")
|
115 |
-
|
116 |
|
117 |
# Add author info in the sidebar
|
118 |
with st.sidebar:
|
@@ -120,44 +151,8 @@ with st.sidebar:
|
|
120 |
st.markdown("**Vasan Iyer**")
|
121 |
st.markdown("**Eric J Giacomucci**")
|
122 |
st.markdown("[GitHub](https://github.com/Vaiy108)")
|
123 |
-
st.markdown("[LinkedIn](https://linkedin.com/in/vasan-iyer)")
|
124 |
-
|
125 |
-
@track
|
126 |
-
def get_chat_completion_openai(client, prompt: str):
|
127 |
-
return client.chat.completions.create(
|
128 |
-
model="gpt-4o", # or "gpt-4" if you need the older GPT-4
|
129 |
-
messages=[{"role": "user", "content": prompt}],
|
130 |
-
temperature=0.5,
|
131 |
-
max_tokens=150
|
132 |
-
)
|
133 |
-
|
134 |
-
@track
|
135 |
-
def get_similar_prompt(query):
|
136 |
-
text_embeddings = embed_dataset_texts(combined_texts) # cached
|
137 |
-
query_embedding = embed_query_text(query) # recalculated each time
|
138 |
-
|
139 |
-
cos_scores = util.pytorch_cos_sim(query_embedding, text_embeddings)[0]
|
140 |
-
top_result = torch.topk(cos_scores, k=1)
|
141 |
-
idx = top_result.indices[0].item()
|
142 |
-
return data[idx]
|
143 |
-
|
144 |
-
# Cache dataset image embeddings (takes time, so cached)
|
145 |
-
@st.cache_data(show_spinner=True)
|
146 |
-
def embed_dataset_images(_dataset):
|
147 |
-
features = []
|
148 |
-
for item in _dataset:
|
149 |
-
# Load image from URL/path or raw bytes - adapt this if needed
|
150 |
-
img = item["image"]
|
151 |
-
inputs = clip_processor(images=img, return_tensors="pt")
|
152 |
-
with torch.no_grad():
|
153 |
-
feat = clip_model.get_image_features(**inputs)
|
154 |
-
feat /= feat.norm(p=2, dim=-1, keepdim=True)
|
155 |
-
features.append(feat.cpu())
|
156 |
-
return torch.cat(features, dim=0)
|
157 |
-
|
158 |
-
dataset_image_features = embed_dataset_images(data)
|
159 |
|
160 |
-
#if query:
|
161 |
if st.button("Submit") and query:
|
162 |
with st.spinner("Searching medical cases..."):
|
163 |
|
@@ -172,7 +167,7 @@ if st.button("Submit") and query:
|
|
172 |
st.markdown(f"**Case Description:** {selected[TEXT_COLUMN]}")
|
173 |
|
174 |
# GPT Explanation
|
175 |
-
if
|
176 |
prompt = f"Explain this case in plain English: {selected[TEXT_COLUMN]}"
|
177 |
|
178 |
explanation = get_chat_completion_openai(client, prompt)
|
@@ -182,32 +177,37 @@ if st.button("Submit") and query:
|
|
182 |
else:
|
183 |
st.warning("OpenAI API key not found. Please set OPENAI_API_KEY as a secret environment variable.")
|
184 |
|
185 |
-
if uploaded_file is not None:
|
186 |
-
print('uploading file')
|
187 |
-
print(uploaded_file)
|
188 |
-
query_image = Image.open(uploaded_file).convert("RGB")
|
189 |
-
st.image(query_image, caption="Your uploaded image", use_container_width=True)
|
190 |
|
191 |
-
# Embed uploaded image
|
192 |
-
inputs = clip_processor(images=query_image, return_tensors="pt")
|
193 |
-
with torch.no_grad():
|
194 |
-
query_feat = clip_model.get_image_features(**inputs)
|
195 |
-
query_feat /= query_feat.norm(p=2, dim=-1, keepdim=True)
|
196 |
|
197 |
-
|
198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
|
200 |
-
|
201 |
-
|
202 |
|
203 |
-
|
204 |
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
else:
|
211 |
-
print("no image")
|
212 |
|
213 |
-
st.caption("This chatbot is for educational purposes only and does not provide medical advice.")
|
|
|
2 |
# ✅ Cache-Safe Multimodal App
|
3 |
# ================================
|
4 |
|
5 |
+
import shutil, os
|
6 |
|
7 |
# ====== Force all cache dirs to /tmp (writable in most environments) ======
|
8 |
CACHE_BASE = "/tmp/cache"
|
|
|
13 |
os.environ["TORCH_HOME"] = f"{CACHE_BASE}/torch"
|
14 |
os.environ["STREAMLIT_CACHE_DIR"] = f"{CACHE_BASE}/streamlit_cache"
|
15 |
os.environ["STREAMLIT_STATIC_DIR"] = f"{CACHE_BASE}/streamlit_static"
|
16 |
+
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
|
17 |
+
|
18 |
+
# Create the directories before imports
|
19 |
+
os.makedirs(os.environ["STREAMLIT_CONFIG_DIR"], exist_ok=True)
|
20 |
|
21 |
# Create the directories before imports
|
22 |
for path in os.environ.values():
|
|
|
30 |
from transformers import CLIPProcessor, CLIPModel
|
31 |
from datasets import load_dataset, get_dataset_split_names
|
32 |
from PIL import Image
|
33 |
+
from openai import OpenAI
|
34 |
import comet_llm
|
35 |
from opik import track
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
# ========== 🔑 API Key ==========
|
38 |
+
OpenAI.api_key = os.getenv("OPENAI_API_KEY")
|
39 |
os.environ["OPIK_API_KEY"] = os.getenv("OPIK_API_KEY")
|
40 |
os.environ["OPIK_WORKSPACE"] = os.getenv("OPIK_WORKSPACE")
|
41 |
# ========== 📥 Load Models ==========
|
42 |
@st.cache_resource(show_spinner=False)
|
43 |
def load_models():
|
44 |
+
_clip_model = CLIPModel.from_pretrained(
|
45 |
"openai/clip-vit-base-patch32",
|
46 |
cache_dir=os.environ["TRANSFORMERS_CACHE"]
|
47 |
)
|
48 |
+
_clip_processor = CLIPProcessor.from_pretrained(
|
49 |
"openai/clip-vit-base-patch32",
|
50 |
cache_dir=os.environ["TRANSFORMERS_CACHE"]
|
51 |
)
|
52 |
+
_text_model = SentenceTransformer(
|
53 |
"all-MiniLM-L6-v2",
|
54 |
cache_folder=os.environ["SENTENCE_TRANSFORMERS_HOME"]
|
55 |
)
|
56 |
+
return _clip_model, _clip_processor, _text_model
|
57 |
|
58 |
clip_model, clip_processor, text_model = load_models()
|
59 |
|
|
|
69 |
)
|
70 |
return dataset
|
71 |
|
72 |
+
# Cache dataset image embeddings (takes time, so cached)
|
73 |
+
@st.cache_data(show_spinner=True)
|
74 |
+
def embed_dataset_images(_dataset):
|
75 |
+
features = []
|
76 |
+
for item in _dataset:
|
77 |
+
# Load image from URL/path or raw bytes - adapt this if needed
|
78 |
+
img = item["image"]
|
79 |
+
inputs_img = clip_processor(images=img, return_tensors="pt")
|
80 |
+
with torch.no_grad():
|
81 |
+
feat = clip_model.get_image_features(**inputs_img)
|
82 |
+
feat /= feat.norm(p=2, dim=-1, keepdim=True)
|
83 |
+
features.append(feat.cpu())
|
84 |
+
return torch.cat(features, dim=0)
|
85 |
+
|
86 |
data = load_medical_data()
|
87 |
+
dataset_image_features = embed_dataset_images(data)
|
88 |
|
89 |
+
client = OpenAI(api_key=OpenAI.api_key)
|
|
|
90 |
# Temporary debug display
|
91 |
#st.write("Dataset columns:", data.features.keys())
|
92 |
|
|
|
113 |
def embed_dataset_texts(_texts):
|
114 |
return text_model.encode(_texts, convert_to_tensor=True)
|
115 |
|
116 |
+
def embed_query_text(_query):
|
117 |
+
return text_model.encode([_query], convert_to_tensor=True)[0]
|
118 |
+
|
119 |
+
@track
|
120 |
+
def get_chat_completion_openai(_client, _prompt: str):
|
121 |
+
return _client.chat.completions.create(
|
122 |
+
model="gpt-4o", # or "gpt-4" if you need the older GPT-4
|
123 |
+
messages=[{"role": "user", "content": _prompt}],
|
124 |
+
temperature=0.5,
|
125 |
+
max_tokens=425
|
126 |
+
)
|
127 |
+
|
128 |
+
@track
|
129 |
+
def get_similar_prompt(_query):
|
130 |
+
text_embeddings = embed_dataset_texts(combined_texts) # cached
|
131 |
+
query_embedding = embed_query_text(_query) # recalculated each time
|
132 |
+
|
133 |
+
cos_scores = util.pytorch_cos_sim(query_embedding, text_embeddings)[0]
|
134 |
+
top_result = torch.topk(cos_scores, k=1)
|
135 |
+
_idx = top_result.indices[0].item()
|
136 |
+
return data[_idx]
|
137 |
+
|
138 |
|
139 |
# Pick which text column to use
|
140 |
TEXT_COLUMN = "complaints" # or "general_complaint", depending on your needs
|
141 |
|
142 |
# ========== 🧑⚕️ App UI ==========
|
143 |
+
st.title("🩺 Multimodal Medical Chatbot")
|
144 |
|
145 |
query = st.text_input("Enter your medical question or symptom description:")
|
146 |
+
uploaded_files = st.file_uploader("Upload an image to find similar medical cases:", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
|
147 |
|
148 |
# Add author info in the sidebar
|
149 |
with st.sidebar:
|
|
|
151 |
st.markdown("**Vasan Iyer**")
|
152 |
st.markdown("**Eric J Giacomucci**")
|
153 |
st.markdown("[GitHub](https://github.com/Vaiy108)")
|
154 |
+
st.markdown("[LinkedIn](https://linkedin.com/in/vasan-iyer)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
|
|
156 |
if st.button("Submit") and query:
|
157 |
with st.spinner("Searching medical cases..."):
|
158 |
|
|
|
167 |
st.markdown(f"**Case Description:** {selected[TEXT_COLUMN]}")
|
168 |
|
169 |
# GPT Explanation
|
170 |
+
if OpenAI.api_key:
|
171 |
prompt = f"Explain this case in plain English: {selected[TEXT_COLUMN]}"
|
172 |
|
173 |
explanation = get_chat_completion_openai(client, prompt)
|
|
|
177 |
else:
|
178 |
st.warning("OpenAI API key not found. Please set OPENAI_API_KEY as a secret environment variable.")
|
179 |
|
|
|
|
|
|
|
|
|
|
|
180 |
|
|
|
|
|
|
|
|
|
|
|
181 |
|
182 |
+
if uploaded_files is not None:
|
183 |
+
with st.spinner("Searching medical cases..."):
|
184 |
+
st.write(f"Number of files: {len(uploaded_files)}")
|
185 |
+
|
186 |
+
if len(uploaded_files) > 0:
|
187 |
+
print(uploaded_files)
|
188 |
+
uploaded_file = uploaded_files[0]
|
189 |
+
st.write(f'uploading file {uploaded_file.name}')
|
190 |
+
query_image = Image.open(uploaded_file).convert("RGB")
|
191 |
+
st.image(query_image, caption="Your uploaded image", use_container_width=True)
|
192 |
+
|
193 |
+
# Embed uploaded image
|
194 |
+
inputs = clip_processor(images=query_image, return_tensors="pt")
|
195 |
+
with torch.no_grad():
|
196 |
+
query_feat = clip_model.get_image_features(**inputs)
|
197 |
+
query_feat /= query_feat.norm(p=2, dim=-1, keepdim=True)
|
198 |
+
|
199 |
+
# Compute cosine similarity
|
200 |
+
similarities = (dataset_image_features @ query_feat.T).squeeze(1) # [num_dataset_images]
|
201 |
|
202 |
+
top_k = 3
|
203 |
+
top_results = torch.topk(similarities, k=top_k)
|
204 |
|
205 |
+
st.write(f"Top {top_k} similar medical cases:")
|
206 |
|
207 |
+
for rank, idx in enumerate(top_results.indices):
|
208 |
+
score = top_results.values[rank].item()
|
209 |
+
similar_img = data[int(idx)]['image']
|
210 |
+
st.image(similar_img, caption=f"Similarity: {score:.3f}", use_container_width=True)
|
211 |
+
st.markdown(f"**Case description:** {data[int(idx)]['complaints']}")
|
|
|
|
|
212 |
|
213 |
+
st.caption("This chatbot is for educational purposes only and does not provide medical advice.")
|