Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- README.md +28 -19
- app.py +404 -0
- cancer_cnn.pt +3 -0
- phikon_head.pt +3 -0
- requirements.txt +10 -2
- svm_model.pkl +3 -0
README.md
CHANGED
|
@@ -1,19 +1,28 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Multi Cancer Detection
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
## Problem
|
| 6 |
+
|
| 7 |
+
I want to create model(s) that are able to distinguish the patterns and features from cancer images. The main goal isn't just to test accuracy but to test whether or not the model can correctly predict an image with any quality. The dataset contains high quality cancer images ranging from MRI scans to histopathology imaging. There will be some uncertainties with this and I don't expect any model to have a perfect guess for every picture. Regardless the prediction should be close or not at all.
|
| 8 |
+
|
| 9 |
+
## Dataset
|
| 10 |
+
|
| 11 |
+
Dataset Link: https://www.kaggle.com/datasets/obulisainaren/multi-cancer
|
| 12 |
+
Within the dataset contains 8 types of cancers found in specific organs. There is 26 distinct types of cancers in this 8 class cancer types. The cancers are Leukemia, Brain Cancer, Breast Cancer, Cervical Cancer, Kidney Cancer, Lung Cancer and Colon Cancer, Lymphoma, and Oral Cancer.
|
| 13 |
+
|
| 14 |
+
## Models
|
| 15 |
+
|
| 16 |
+
4 models are used within Project 2.
|
| 17 |
+
|
| 18 |
+
SVM that is trained on ResNet18 embeddings using Image2Vec.
|
| 19 |
+
|
| 20 |
+
A CNN trained on a portion of the dataset that is an optimized version from Project 1, this CNN uses data augmentation, ReduceLROnPlateau, and useful paddings.
|
| 21 |
+
|
| 22 |
+
I could not find a 2nd LLM that is supported by unsloth as the other models had over 4B parameters that ranged to 8B to 11B. Therefore, I compensated with a ViT that was specifically made for medical imaging. https://huggingface.co/owkin/phikon. I imported the model and then trained it on a portion of my dataset and it yielded the best results.
|
| 23 |
+
|
| 24 |
+
LLM link: https://huggingface.co/Qwen/Qwen3-VL-2B-Instruct. This LLM was not exposed to much of the data due to the computational strain it puts on Kaggle's VRAM and RAM. A lot of the training sessions would time out due to the RAM/VRAM going above the limit. The situation was more difficult due to Unsloth not supporting multi-GPUs. Therefore, the LLM will not perform as well as the other models but what is more important is the prediction it will give and seeing how close that prediction really is.
|
| 25 |
+
|
| 26 |
+
## Results
|
| 27 |
+
|
| 28 |
+
Training an VLLM is difficult due to the amount of computation time and limitations of hardware. Not every problem needs to be solved with an LLM, however, an LLM is more state of the art and more trendier these days. To handle an LLM would provide benefits as there will be benefits as a user can directly interact with the LLM to figure out what is happening with their scan of whatever cancer they have. But, I don't see a world where VLLMs can provide a more beneficial access to information than doctors who are trained for years and have experience within the scope of identifying a cancer image. Regardless better algorithms or models can cover the computational cost if we are simply identifying a form of cancer.
|
app.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pickle
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import gc
|
| 8 |
+
import os
|
| 9 |
+
from torchvision.transforms import v2 as T
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
# ββ Page Configuration ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
+
st.set_page_config(
|
| 14 |
+
page_title="Cancer Histopathology Classifier",
|
| 15 |
+
page_icon="π¬",
|
| 16 |
+
layout="wide"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# ββ Device (forced CPU) ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
device = torch.device("cpu")
|
| 21 |
+
|
| 22 |
+
# ββ Class names (26 cancer types) βββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
+
CLASS_NAMES = [
|
| 24 |
+
"all_benign", "all_early", "all_pre", "all_pro",
|
| 25 |
+
"brain_glioma", "brain_menin", "brain_tumor",
|
| 26 |
+
"breast_benign", "breast_malignant",
|
| 27 |
+
"cervix_dyk", "cervix_koc", "cervix_mep", "cervix_pab", "cervix_sfi",
|
| 28 |
+
"colon_aca", "colon_bnt",
|
| 29 |
+
"kidney_normal", "kidney_tumor",
|
| 30 |
+
"lung_aca", "lung_bnt", "lung_scc",
|
| 31 |
+
"lymph_cll", "lymph_fl", "lymph_mcl",
|
| 32 |
+
"oral_normal", "oral_scc",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# ββ Local path to fine-tuned Qwen adapter βββββββββββββββββββββββββββββββββββ
|
| 36 |
+
QWEN_LOCAL_PATH = "qwen-cancer-finetuned"
|
| 37 |
+
|
| 38 |
+
# ββ CancerCNN ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
class CancerCNN(nn.Module):
|
| 40 |
+
def __init__(self, num_classes=26):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.layers = nn.Sequential(
|
| 43 |
+
nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(),
|
| 44 |
+
nn.Conv2d(16, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(),
|
| 45 |
+
nn.MaxPool2d(2),
|
| 46 |
+
nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
|
| 47 |
+
nn.MaxPool2d(2),
|
| 48 |
+
nn.Conv2d(32, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
|
| 49 |
+
nn.Flatten(),
|
| 50 |
+
nn.Dropout(0.3),
|
| 51 |
+
nn.Linear(32 * 28 * 28, num_classes),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
return self.layers(x)
|
| 56 |
+
|
| 57 |
+
# ββ Phikon classifier head βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 58 |
+
class PhikonHead(nn.Module):
|
| 59 |
+
def __init__(self, num_classes=26):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.head = nn.Linear(768, num_classes)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
return self.head(x)
|
| 65 |
+
|
| 66 |
+
# ββ Lazy model cache βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
if "model_cache" not in st.session_state:
|
| 68 |
+
st.session_state.model_cache = {"name": None, "model": None, "extra": None}
|
| 69 |
+
|
| 70 |
+
def _evict():
|
| 71 |
+
st.session_state.model_cache["name"] = None
|
| 72 |
+
st.session_state.model_cache["model"] = None
|
| 73 |
+
st.session_state.model_cache["extra"] = None
|
| 74 |
+
gc.collect()
|
| 75 |
+
|
| 76 |
+
# ββ Transforms βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
+
cnn_transform = T.Compose([
|
| 78 |
+
T.Resize((112, 112)),
|
| 79 |
+
T.ToImage(),
|
| 80 |
+
T.ToDtype(torch.float32, scale=True),
|
| 81 |
+
T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 82 |
+
])
|
| 83 |
+
|
| 84 |
+
phikon_transform = T.Compose([
|
| 85 |
+
T.Resize((224, 224)),
|
| 86 |
+
T.ToImage(),
|
| 87 |
+
T.ToDtype(torch.float32, scale=True),
|
| 88 |
+
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 89 |
+
])
|
| 90 |
+
|
| 91 |
+
# ββ Model loaders βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
def load_cnn():
|
| 93 |
+
if st.session_state.model_cache["name"] == "cnn":
|
| 94 |
+
return st.session_state.model_cache["model"]
|
| 95 |
+
_evict()
|
| 96 |
+
m = CancerCNN(num_classes=26)
|
| 97 |
+
m.load_state_dict(torch.load("cancer_cnn.pt", map_location=device), strict=False)
|
| 98 |
+
m.eval().to(device)
|
| 99 |
+
st.session_state.model_cache["name"] = "cnn"
|
| 100 |
+
st.session_state.model_cache["model"] = m
|
| 101 |
+
return m
|
| 102 |
+
|
| 103 |
+
def load_svm():
|
| 104 |
+
if st.session_state.model_cache["name"] == "svm":
|
| 105 |
+
return st.session_state.model_cache["model"], st.session_state.model_cache["extra"]
|
| 106 |
+
_evict()
|
| 107 |
+
with open("svm_model.pkl", "rb") as f:
|
| 108 |
+
svm = pickle.load(f)
|
| 109 |
+
from img2vec_pytorch import Img2Vec
|
| 110 |
+
img2vec = Img2Vec(cuda=False)
|
| 111 |
+
st.session_state.model_cache["name"] = "svm"
|
| 112 |
+
st.session_state.model_cache["model"] = svm
|
| 113 |
+
st.session_state.model_cache["extra"] = img2vec
|
| 114 |
+
return svm, img2vec
|
| 115 |
+
|
| 116 |
+
def load_qwen():
|
| 117 |
+
if st.session_state.model_cache["name"] == "qwen":
|
| 118 |
+
return st.session_state.model_cache["model"], st.session_state.model_cache["extra"]
|
| 119 |
+
_evict()
|
| 120 |
+
|
| 121 |
+
if not os.path.isdir(QWEN_LOCAL_PATH):
|
| 122 |
+
raise FileNotFoundError(
|
| 123 |
+
f"Expected local Qwen adapter folder at '{QWEN_LOCAL_PATH}' but it "
|
| 124 |
+
f"was not found."
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
|
| 128 |
+
from peft import PeftModel
|
| 129 |
+
|
| 130 |
+
# Load base model
|
| 131 |
+
base_model_id = "Qwen/Qwen2-VL-2B-Instruct"
|
| 132 |
+
base_model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 133 |
+
base_model_id,
|
| 134 |
+
torch_dtype=torch.float32,
|
| 135 |
+
device_map=None,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Layer the adapter on top
|
| 139 |
+
model = PeftModel.from_pretrained(base_model, QWEN_LOCAL_PATH)
|
| 140 |
+
model.to(device)
|
| 141 |
+
model.eval()
|
| 142 |
+
|
| 143 |
+
processor = AutoProcessor.from_pretrained(QWEN_LOCAL_PATH)
|
| 144 |
+
|
| 145 |
+
st.session_state.model_cache["name"] = "qwen"
|
| 146 |
+
st.session_state.model_cache["model"] = model
|
| 147 |
+
st.session_state.model_cache["extra"] = processor
|
| 148 |
+
return model, processor
|
| 149 |
+
|
| 150 |
+
def load_phikon():
|
| 151 |
+
if st.session_state.model_cache["name"] == "phikon":
|
| 152 |
+
return st.session_state.model_cache["model"], st.session_state.model_cache["extra"]
|
| 153 |
+
_evict()
|
| 154 |
+
from transformers import AutoModel
|
| 155 |
+
backbone = AutoModel.from_pretrained("owkin/phikon").to(device)
|
| 156 |
+
backbone.eval()
|
| 157 |
+
head = PhikonHead(num_classes=26).to(device)
|
| 158 |
+
|
| 159 |
+
ckpt = torch.load("phikon_head.pt", map_location=device)
|
| 160 |
+
state_dict = ckpt.get("head_state_dict", ckpt)
|
| 161 |
+
|
| 162 |
+
mapped_state_dict = {}
|
| 163 |
+
for k, v in state_dict.items():
|
| 164 |
+
if k == "weight":
|
| 165 |
+
mapped_state_dict["head.weight"] = v
|
| 166 |
+
elif k == "bias":
|
| 167 |
+
mapped_state_dict["head.bias"] = v
|
| 168 |
+
else:
|
| 169 |
+
mapped_state_dict[k] = v
|
| 170 |
+
|
| 171 |
+
head.load_state_dict(mapped_state_dict, strict=False)
|
| 172 |
+
head.eval()
|
| 173 |
+
|
| 174 |
+
st.session_state.model_cache["name"] = "phikon"
|
| 175 |
+
st.session_state.model_cache["model"] = backbone
|
| 176 |
+
st.session_state.model_cache["extra"] = head
|
| 177 |
+
return backbone, head
|
| 178 |
+
|
| 179 |
+
# ββ Inference functions βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 180 |
+
def predict_cnn(image: Image.Image):
|
| 181 |
+
model = load_cnn()
|
| 182 |
+
x = cnn_transform(image).unsqueeze(0).to(device)
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
logits = model(x)
|
| 185 |
+
probs = torch.softmax(logits, dim=1)[0]
|
| 186 |
+
top3 = probs.topk(3)
|
| 187 |
+
result = {CLASS_NAMES[i]: float(p) for i, p in zip(top3.indices, top3.values)}
|
| 188 |
+
pred = CLASS_NAMES[probs.argmax().item()]
|
| 189 |
+
return pred, result
|
| 190 |
+
|
| 191 |
+
def predict_svm(image: Image.Image):
|
| 192 |
+
svm, img2vec = load_svm()
|
| 193 |
+
vec = img2vec.get_vec(image, tensor=False).reshape(1, -1)
|
| 194 |
+
|
| 195 |
+
raw_pred = svm.predict(vec)[0]
|
| 196 |
+
try:
|
| 197 |
+
pred = CLASS_NAMES[int(raw_pred)]
|
| 198 |
+
except (ValueError, TypeError):
|
| 199 |
+
pred = str(raw_pred)
|
| 200 |
+
|
| 201 |
+
proba = svm.predict_proba(vec)[0] if hasattr(svm, "predict_proba") else None
|
| 202 |
+
|
| 203 |
+
if proba is not None:
|
| 204 |
+
top3_idx = np.argsort(proba)[-3:][::-1]
|
| 205 |
+
result = {CLASS_NAMES[i]: float(proba[i]) for i in top3_idx}
|
| 206 |
+
else:
|
| 207 |
+
result = {pred: 1.0}
|
| 208 |
+
|
| 209 |
+
return pred, result
|
| 210 |
+
|
| 211 |
+
def predict_phikon(image: Image.Image):
|
| 212 |
+
backbone, head = load_phikon()
|
| 213 |
+
x = phikon_transform(image).unsqueeze(0).to(device)
|
| 214 |
+
with torch.no_grad():
|
| 215 |
+
features = backbone(x).last_hidden_state[:, 0, :]
|
| 216 |
+
logits = head(features)
|
| 217 |
+
probs = torch.softmax(logits, dim=1)[0]
|
| 218 |
+
top3 = probs.topk(3)
|
| 219 |
+
result = {CLASS_NAMES[i]: float(p) for i, p in zip(top3.indices, top3.values)}
|
| 220 |
+
pred = CLASS_NAMES[probs.argmax().item()]
|
| 221 |
+
return pred, result
|
| 222 |
+
|
| 223 |
+
def predict_qwen_chat(chat_history):
|
| 224 |
+
"""Processes the full conversation history for Qwen2-VL"""
|
| 225 |
+
model, processor = load_qwen()
|
| 226 |
+
|
| 227 |
+
qwen_msgs = []
|
| 228 |
+
images = []
|
| 229 |
+
|
| 230 |
+
# 1. Figure out if the user is asking a follow-up or classifying a new image
|
| 231 |
+
is_follow_up_chat = True
|
| 232 |
+
if len(chat_history) > 0:
|
| 233 |
+
latest_msg = chat_history[-1]
|
| 234 |
+
if "image" in latest_msg:
|
| 235 |
+
is_follow_up_chat = False # It has an image, so it's a classification task
|
| 236 |
+
|
| 237 |
+
# 2. Rebuild the history
|
| 238 |
+
for msg in chat_history:
|
| 239 |
+
content = []
|
| 240 |
+
if msg.get("image"):
|
| 241 |
+
content.append({"type": "image", "image": msg["image"]})
|
| 242 |
+
images.append(msg["image"])
|
| 243 |
+
|
| 244 |
+
if msg.get("text"):
|
| 245 |
+
content.append({"type": "text", "text": msg["text"]})
|
| 246 |
+
|
| 247 |
+
qwen_msgs.append({"role": msg["role"], "content": content})
|
| 248 |
+
|
| 249 |
+
input_text = processor.apply_chat_template(qwen_msgs, add_generation_prompt=True)
|
| 250 |
+
|
| 251 |
+
if len(images) > 0:
|
| 252 |
+
inputs = processor(images=images, text=input_text, return_tensors="pt").to(device)
|
| 253 |
+
else:
|
| 254 |
+
inputs = processor(text=input_text, return_tensors="pt").to(device)
|
| 255 |
+
|
| 256 |
+
with torch.no_grad():
|
| 257 |
+
# 3. THE MAGIC TRICK: Turn off the adapter for regular text chat!
|
| 258 |
+
if is_follow_up_chat and hasattr(model, "disable_adapter"):
|
| 259 |
+
with model.disable_adapter():
|
| 260 |
+
output = model.generate(**inputs, max_new_tokens=300)
|
| 261 |
+
else:
|
| 262 |
+
# Leave adapter on for image classification
|
| 263 |
+
output = model.generate(**inputs, max_new_tokens=200)
|
| 264 |
+
|
| 265 |
+
response = processor.decode(output[0], skip_special_tokens=True)
|
| 266 |
+
|
| 267 |
+
if "assistant" in response.lower():
|
| 268 |
+
response = response.split("assistant")[-1].strip()
|
| 269 |
+
|
| 270 |
+
return response
|
| 271 |
+
|
| 272 |
+
# ββ Main standard inference dispatcher ββββββββββββββββββββββββββββββββββββββββ
|
| 273 |
+
def classify(pil_image, model_choice):
|
| 274 |
+
if model_choice == "CancerCNN":
|
| 275 |
+
pred, probs = predict_cnn(pil_image)
|
| 276 |
+
explanation = f"**CancerCNN predicted:** {pred}\n\nThis is a custom CNN trained from scratch on 26 cancer types with BatchNorm, Dropout, and data augmentation. It achieved 84.79% test accuracy."
|
| 277 |
+
return pred, probs, explanation
|
| 278 |
+
|
| 279 |
+
elif model_choice == "SVM (img2vec)":
|
| 280 |
+
pred, probs = predict_svm(pil_image)
|
| 281 |
+
explanation = f"**SVM predicted:** {pred}\n\nThis Support Vector Machine uses ResNet18 embeddings (via img2vec) as features. Classical ML approach β no deep learning training required."
|
| 282 |
+
return pred, probs, explanation
|
| 283 |
+
|
| 284 |
+
elif model_choice == "Phikon (ViT-B Histopathology)":
|
| 285 |
+
pred, probs = predict_phikon(pil_image)
|
| 286 |
+
explanation = f"**Phikon predicted:** {pred}\n\nPhikon is a ViT-Base model pretrained on 40M pan-cancer histopathology tiles from TCGA using self-supervised learning. It extracts domain-specific features far beyond what ImageNet-pretrained models can capture."
|
| 287 |
+
return pred, probs, explanation
|
| 288 |
+
|
| 289 |
+
return "Unknown model", {}, ""
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ββ Streamlit UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 293 |
+
st.title("π¬ Cancer Histopathology Classifier")
|
| 294 |
+
st.markdown("""
|
| 295 |
+
Upload a histopathology image and select a model to classify the cancer type across 26 categories.
|
| 296 |
+
β οΈ *Running on CPU β Deep learning inference may take a moment.*
|
| 297 |
+
""")
|
| 298 |
+
|
| 299 |
+
# High-level model selection controls the entire UI layout
|
| 300 |
+
model_choice = st.selectbox(
|
| 301 |
+
"Select Model",
|
| 302 |
+
["CancerCNN", "SVM (img2vec)", "Phikon (ViT-B Histopathology)", "Qwen2-VL-2B (Fine-tuned)"]
|
| 303 |
+
)
|
| 304 |
+
st.markdown("---")
|
| 305 |
+
|
| 306 |
+
if model_choice == "Qwen2-VL-2B (Fine-tuned)":
|
| 307 |
+
# ββ QWEN CHAT UI (GEMINI STYLE) βββββββββββββββββββββββββββββββββββββββββββ
|
| 308 |
+
st.subheader("π¬ Qwen2-VL Analysis Chat")
|
| 309 |
+
|
| 310 |
+
# Initialize chat history
|
| 311 |
+
if "qwen_messages" not in st.session_state:
|
| 312 |
+
st.session_state.qwen_messages = []
|
| 313 |
+
|
| 314 |
+
# Display existing chat history
|
| 315 |
+
chat_container = st.container()
|
| 316 |
+
with chat_container:
|
| 317 |
+
for msg in st.session_state.qwen_messages:
|
| 318 |
+
with st.chat_message(msg["role"]):
|
| 319 |
+
if msg.get("image"):
|
| 320 |
+
st.image(msg["image"], width=300)
|
| 321 |
+
if msg.get("text"):
|
| 322 |
+
st.markdown(msg["text"])
|
| 323 |
+
|
| 324 |
+
# The Attachment & Chat Input Area
|
| 325 |
+
st.caption("π Attach an image for your next message:")
|
| 326 |
+
chat_image_upload = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"], label_visibility="collapsed")
|
| 327 |
+
|
| 328 |
+
# Input box (with the auto-prompt injection logic we discussed)
|
| 329 |
+
if prompt := st.chat_input("Message Qwen... (e.g., 'What type of cancer is this?')"):
|
| 330 |
+
|
| 331 |
+
# If they just uploaded an image and hit enter without typing, auto-fill the training prompt
|
| 332 |
+
if not prompt.strip() and chat_image_upload is not None:
|
| 333 |
+
prompt = "What type of cancer is shown in this histopathology image?"
|
| 334 |
+
|
| 335 |
+
user_msg = {"role": "user", "text": prompt}
|
| 336 |
+
|
| 337 |
+
# Attach image only if it's new (prevents re-uploading the same image on follow-up questions)
|
| 338 |
+
if chat_image_upload is not None:
|
| 339 |
+
file_sig = f"{chat_image_upload.name}_{chat_image_upload.size}"
|
| 340 |
+
if st.session_state.get("last_uploaded_qwen_file") != file_sig:
|
| 341 |
+
user_msg["image"] = Image.open(chat_image_upload).convert("RGB")
|
| 342 |
+
st.session_state.last_uploaded_qwen_file = file_sig
|
| 343 |
+
|
| 344 |
+
# Append and display user message
|
| 345 |
+
st.session_state.qwen_messages.append(user_msg)
|
| 346 |
+
with chat_container:
|
| 347 |
+
with st.chat_message("user"):
|
| 348 |
+
if user_msg.get("image"):
|
| 349 |
+
st.image(user_msg["image"], width=300)
|
| 350 |
+
st.markdown(prompt)
|
| 351 |
+
|
| 352 |
+
# Generate and display assistant response
|
| 353 |
+
with st.chat_message("assistant"):
|
| 354 |
+
with st.spinner("Qwen is analyzing..."):
|
| 355 |
+
try:
|
| 356 |
+
response = predict_qwen_chat(st.session_state.qwen_messages)
|
| 357 |
+
st.markdown(response)
|
| 358 |
+
st.session_state.qwen_messages.append({"role": "assistant", "text": response})
|
| 359 |
+
except Exception as e:
|
| 360 |
+
st.error(f"An error occurred: {e}")
|
| 361 |
+
|
| 362 |
+
else:
|
| 363 |
+
# ββ STANDARD UI (CNN, SVM, PHIKON) ββββββββββββββββββββββββββββββββββββββββ
|
| 364 |
+
col1, col2 = st.columns(2)
|
| 365 |
+
|
| 366 |
+
with col1:
|
| 367 |
+
st.subheader("Input")
|
| 368 |
+
uploaded_file = st.file_uploader("Upload Histopathology Image", type=["jpg", "jpeg", "png"])
|
| 369 |
+
|
| 370 |
+
classify_btn = st.button("Classify Image", type="primary", use_container_width=True)
|
| 371 |
+
|
| 372 |
+
if uploaded_file is not None:
|
| 373 |
+
image = Image.open(uploaded_file).convert("RGB")
|
| 374 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 375 |
+
|
| 376 |
+
with col2:
|
| 377 |
+
st.subheader("Results")
|
| 378 |
+
if classify_btn:
|
| 379 |
+
if uploaded_file is None:
|
| 380 |
+
st.warning("Please upload an image first.")
|
| 381 |
+
else:
|
| 382 |
+
with st.spinner(f"Running inference with {model_choice}..."):
|
| 383 |
+
try:
|
| 384 |
+
pred, probs, explanation = classify(image, model_choice)
|
| 385 |
+
|
| 386 |
+
st.success(f"**Predicted Cancer Type:** {pred}")
|
| 387 |
+
|
| 388 |
+
if probs:
|
| 389 |
+
st.markdown("**Top Predictions:**")
|
| 390 |
+
df_probs = pd.DataFrame(
|
| 391 |
+
list(probs.values()),
|
| 392 |
+
index=list(probs.keys()),
|
| 393 |
+
columns=["Confidence"]
|
| 394 |
+
)
|
| 395 |
+
st.bar_chart(df_probs)
|
| 396 |
+
|
| 397 |
+
st.markdown("### Model Explanation")
|
| 398 |
+
st.info(explanation)
|
| 399 |
+
|
| 400 |
+
except Exception as e:
|
| 401 |
+
st.error(f"An error occurred during inference: {e}")
|
| 402 |
+
|
| 403 |
+
st.markdown("---")
|
| 404 |
+
st.markdown("**Dataset:** [Multi-Cancer Dataset](https://www.kaggle.com/datasets/obulisainaren/multi-cancer) β 130K images, 26 cancer types")
|
cancer_cnn.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:afaa94e45e3447f1f2a0938507128e1985feeedaf419c1020ea3f95af0992afb
|
| 3 |
+
size 2688181
|
phikon_head.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d3783046f5b76cf17fa2916b5e85287e06908aeac32eefca8ca6ba501455222c
|
| 3 |
+
size 82373
|
requirements.txt
CHANGED
|
@@ -1,3 +1,11 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 2 |
pandas
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|
| 4 |
+
numpy
|
| 5 |
pandas
|
| 6 |
+
Pillow
|
| 7 |
+
transformers
|
| 8 |
+
peft
|
| 9 |
+
accelerate
|
| 10 |
+
scikit-learn
|
| 11 |
+
img2vec-pytorch
|
svm_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:80387b9f5e3c2821728aabf56b8e788b36f2ccf2a3365611099c03354394d045
|
| 3 |
+
size 45656991
|