MoritzMMuller commited on
Commit
e7cb354
·
verified ·
1 Parent(s): 29eafb1

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +337 -0
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from PIL import Image
4
+ import pandas as pd
5
+ from datetime import datetime
6
+ from transformers import (
7
+ AutoFeatureExtractor,
8
+ AutoModelForImageClassification,
9
+ AutoTokenizer,
10
+ AutoModelForSeq2SeqLM,
11
+ pipeline,
12
+ Qwen2VLForConditionalGeneration, Qwen2VLProcessor,
13
+ )
14
+ import requests
15
+ from geopy.geocoders import Nominatim
16
+ import folium
17
+ from streamlit_folium import st_folium
18
+ import cv2
19
+ import numpy as np
20
+
21
+
22
+ st.set_page_config(page_title="Skin Cancer Dashboard", layout="wide")
23
+
24
+ # --- Configuration ---
25
+ # Ensure you have set your Hugging Face token as an environment variable:
26
+ # export HF_TOKEN="YOUR_TOKEN_HERE"
27
+ MODEL_NAME = "Anwarkh1/Skin_Cancer-Image_Classification"
28
+ LLM_NAME = "google/flan-t5-xl"
29
+ HF_TOKEN = ".."
30
+ DATA_DIR = "data/harvard_dataset" # Path where you download and unpack the Harvard Dataverse dataset
31
+ DIARY_CSV = "diary.csv"
32
+ CANCER_DIR = r"D:\Models\googleflan-t5-xl"
33
+ LLM_DIR = r"D:\Models\SkinCancer"
34
+
35
+ # Initialize session state defaults
36
+ if 'initialized' not in st.session_state:
37
+ st.session_state['label'] = None
38
+ st.session_state['score'] = None
39
+ st.session_state['mole_id'] = ''
40
+ st.session_state['geo_location'] = ''
41
+ st.session_state['chat_history'] = []
42
+ st.session_state['initialized'] = True
43
+
44
+ # Initialize geolocator for free geocoding
45
+ geolocator = Nominatim(user_agent="skin-dashboard", timeout = 10)
46
+
47
+ # --- Load Model & Feature Extractor ---
48
+ @st.cache_resource
49
+ def load_image_model(token: str):
50
+ extractor = AutoFeatureExtractor.from_pretrained(
51
+ MODEL_NAME,
52
+ use_auth_token=token
53
+ )
54
+ model = AutoModelForImageClassification.from_pretrained(
55
+ MODEL_NAME,
56
+ use_auth_token=token
57
+ )
58
+ return pipeline(
59
+ "image-classification",
60
+ model=model,
61
+ feature_extractor=extractor,
62
+ device=0 # set to GPU index or -1 for CPU
63
+ )
64
+
65
+ @st.cache_resource
66
+ def load_llm(token: str):
67
+
68
+ tokenizer = AutoTokenizer.from_pretrained(
69
+ LLM_NAME,
70
+ use_auth_token=token
71
+ )
72
+ # Use Seq2SeqLM for T5-style (text2text) models:
73
+ model = AutoModelForSeq2SeqLM.from_pretrained(
74
+ LLM_NAME,
75
+ use_auth_token=token,
76
+ )
77
+ return pipeline(
78
+ "text2text-generation",
79
+ model=model,
80
+ tokenizer=tokenizer,
81
+ device_map="auto", # or device=0 for single GPU / -1 for CPU
82
+ max_length=10000,
83
+ num_beams=5,
84
+ no_repeat_ngram_size=2,
85
+ early_stopping=True,
86
+
87
+ )
88
+ classifier = load_image_model(HF_TOKEN) if HF_TOKEN else None
89
+ explainer = load_llm(HF_TOKEN) if HF_TOKEN else None
90
+
91
+ # --- Diary Init ----
92
+
93
+ if not os.path.exists(DIARY_CSV):
94
+ pd.DataFrame(
95
+ columns=["timestamp", "image_path", "mole_id", "geo_location", "label", "score",
96
+ "body_location", "prior_consultation", "pain", "itch"]
97
+ ).to_csv(DIARY_CSV, index=False)
98
+
99
+ # --- Save entry helper
100
+
101
+ def save_entry(img_path: str, mole_id: str, geo_location: str,
102
+ label: str, score: float,
103
+ body_location: str, prior_consult: str, pain: str, itch: str):
104
+ df = pd.read_csv(DIARY_CSV)
105
+ entry = {
106
+ "timestamp": datetime.now().isoformat(),
107
+ "image_path": img_path,
108
+ "mole_id": mole_id,
109
+ "geo_location": geo_location,
110
+ "label": label,
111
+ "score": float(score),
112
+ "body_location": body_location,
113
+ "prior_consultation": prior_consult,
114
+ "pain": pain,
115
+ "itch": itch
116
+ }
117
+ df.loc[len(df)] = entry
118
+ df.to_csv(DIARY_CSV, index=False)
119
+
120
+ # --- Preprocessing Functions ---
121
+ def remove_hair(img: np.ndarray) -> np.ndarray:
122
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
123
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 17))
124
+ blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, kernel)
125
+ _, mask = cv2.threshold(blackhat, 10, 255, cv2.THRESH_BINARY)
126
+ return cv2.inpaint(img, mask, 1, cv2.INPAINT_TELEA)
127
+
128
+
129
+ def preprocess(img: Image.Image, size: int = 224) -> Image.Image:
130
+ arr = np.array(img)
131
+ bgr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
132
+ bgr = remove_hair(bgr)
133
+ bgr = cv2.bilateralFilter(bgr, d=9, sigmaColor=75, sigmaSpace=75)
134
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
135
+ l, a, b = cv2.split(lab)
136
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
137
+ cl = clahe.apply(l)
138
+ merged = cv2.merge((cl, a, b))
139
+ bgr = cv2.cvtColor(merged, cv2.COLOR_LAB2BGR)
140
+ h, w = bgr.shape[:2]
141
+ scale = size / max(h, w)
142
+ nh, nw = int(h*scale), int(w*scale)
143
+ resized = cv2.resize(bgr, (nw, nh), interpolation=cv2.INTER_AREA)
144
+ canvas = np.full((size, size, 3), 128, dtype=np.uint8)
145
+ top, left = (size-nh)//2, (size-nw)//2
146
+ canvas[top:top+nh, left:left+nw] = resized
147
+ rgb = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
148
+ return Image.fromarray(rgb)
149
+
150
+ # -----Streamlit layout ----
151
+ st.title("🩺 Skin Cancer Recognition Dashboard")
152
+ menu = ["Scan Mole","Chat","Diary", "Dataset Explorer"]
153
+ choice = st.sidebar.selectbox("Navigation", menu)
154
+
155
+ # --- Initialize Scan a Mole ---
156
+ if choice == "Scan Mole":
157
+ st.header("🔍 Scan a Mole")
158
+ if not classifier:
159
+ st.error("Missing HF_TOKEN.")
160
+ st.stop()
161
+
162
+ upload = st.file_uploader("Upload a skin image", type=["jpg","jpeg","png"])
163
+ if not upload:
164
+ st.info("Please upload an image to begin.")
165
+ st.stop()
166
+
167
+ raw = Image.open(upload).convert("RGB")
168
+ st.image(raw, caption="Original", use_container_width=True)
169
+
170
+ proc = preprocess(raw)
171
+ st.image(proc, caption="Preprocessed", use_container_width=True)
172
+
173
+ mole = st.text_input("Mole ID")
174
+ city = st.text_input("Geographic location")
175
+ body = st.selectbox("Body location", ["Face","Scalp","Neck","Chest","Back","Arm","Hand","Leg","Foot","Other"])
176
+ prior = st.radio("Prior consult?", ["Yes","No"], horizontal=True)
177
+ pain = st.radio("Pain?", ["Yes","No"], horizontal=True)
178
+ itch = st.radio("Itch?", ["Yes","No"], horizontal=True)
179
+
180
+ if st.button("Classify"):
181
+ if not mole or not city:
182
+ st.error("Enter ID and location.")
183
+ else:
184
+ with st.spinner("Analyzing..."):
185
+ out = classifier(proc)
186
+ lbl, scr = out[0]["label"], out[0]["score"]
187
+ save_dir = os.path.join("scans", f"{mole}_{datetime.now().timestamp()}.png")
188
+ os.makedirs(os.path.dirname(save_dir), exist_ok=True)
189
+ raw.save(save_dir)
190
+ save_entry(save_dir, mole, city, lbl, scr, body, prior, pain, itch)
191
+ st.session_state.update({
192
+ 'label': lbl,
193
+ 'score': scr,
194
+ 'mole_id': mole,
195
+ 'geo_location': city
196
+ })
197
+
198
+ if st.session_state['label']:
199
+ st.success(f"Prediction: {st.session_state['label']} (score {st.session_state['score']:.2f})")
200
+ if explainer:
201
+ with st.spinner("Explaining..."):
202
+ text = explainer(f"Explain {st.session_state['label']} and recommendation.")[0]['generated_text']
203
+ st.markdown("### Explanation"); st.write(text)
204
+
205
+ loc = geolocator.geocode(st.session_state['geo_location'])
206
+ if loc:
207
+ m = folium.Map([loc.latitude, loc.longitude], zoom_start=12)
208
+ folium.Marker([loc.latitude, loc.longitude], "You").add_to(m)
209
+ resp = requests.post(
210
+ "https://overpass-api.de/api/interpreter",
211
+ data={"data": f"[out:json];node(around:5000,{loc.latitude},{loc.longitude})[~\"^(amenity|healthcare)$\"~\"clinic|doctors\"];out;"}
212
+ )
213
+ for el in resp.json().get('elements', []):
214
+ tags = el.get('tags', {});
215
+ lat = el.get('lat') or el['center']['lat']; lon = el.get('lon') or el['center']['lon']
216
+ folium.Marker([lat, lon], tags.get('name','Clinic')).add_to(m)
217
+ st.markdown("### Nearby Clinics"); st_folium(m, width=700)
218
+
219
+ # --- Chat Tab ---
220
+ elif choice == "Chat":
221
+ st.header("💬 Follow-Up Chat")
222
+ if not st.session_state['label']:
223
+ st.info("Please perform a scan first in the 'Scan Mole' tab.")
224
+ else:
225
+ lbl = st.session_state['label']
226
+ scr = st.session_state['score']
227
+ mid = st.session_state['mole_id']
228
+ gloc = st.session_state['geo_location']
229
+ st.markdown(f"**Context:** prediction for **{mid}** at **{gloc}** is **{lbl}** (confidence {scr:.2f}).")
230
+
231
+ # New user message comes first for immediate loop
232
+ user_q = st.chat_input("Ask a follow-up question:", key="chat_input")
233
+ if user_q and explainer:
234
+ st.session_state['chat_history'].append({'role':'user','content':user_q})
235
+ system_p = "You are a dermatology assistant. Provide concise medical advice without clarifying questions."
236
+ tpl = (
237
+ f"{system_p}\nContext: prediction is {lbl} with confidence {scr:.2f}.\n"
238
+ f"User: {user_q}\nAssistant:"
239
+ )
240
+ with st.spinner("Generating response..."):
241
+ reply = explainer(tpl)[0]['generated_text']
242
+ st.session_state['chat_history'].append({'role':'assistant','content':reply})
243
+
244
+ # Display the updated chat history
245
+ for msg in st.session_state['chat_history']:
246
+ prefix = 'You' if msg['role']=='user' else 'AI'
247
+ st.markdown(f"**{prefix}:** {msg['content']}")
248
+
249
+
250
+ # --- Diary Page ---
251
+ elif choice == "Diary":
252
+ st.header("📖 Skin Cancer Diary")
253
+ df = pd.read_csv(DIARY_CSV)
254
+ df['timestamp'] = pd.to_datetime(df['timestamp'])
255
+ if df.empty:
256
+ st.info("No diary entries yet.")
257
+ else:
258
+ mole_ids = sorted(df['mole_id'].unique())
259
+ sel = st.selectbox("Select Mole to View", ['All'] + mole_ids, key="diary_sel")
260
+ if sel == 'All':
261
+ # Display moles in columns (max 3 per row)
262
+ chunks = [mole_ids[i:i+3] for i in range(0, len(mole_ids), 3)]
263
+ for group in chunks:
264
+ cols = st.columns(len(group))
265
+ for col, mid in zip(cols, group):
266
+ with col:
267
+ st.subheader(mid)
268
+ entries = df[df['mole_id'] == mid].sort_values('timestamp')
269
+ # Show image timeline
270
+ for _, row in entries.iterrows():
271
+ if os.path.exists(row['image_path']):
272
+ st.image(
273
+ row['image_path'],
274
+ width=150,
275
+ caption=f"{row['timestamp'].strftime('%Y-%m-%d')} — {row['score']:.2f}"
276
+ )
277
+ st.write(f"Total scans: {len(entries)}")
278
+ else:
279
+ # Detailed view for a single mole
280
+ entries = df[df['mole_id'] == sel].sort_values('timestamp')
281
+ if entries.empty:
282
+ st.warning(f"No entries for {sel}.")
283
+ else:
284
+ # Score over time
285
+ st.line_chart(entries.set_index('timestamp')['score'])
286
+ st.markdown("#### Image Timeline")
287
+ for _, row in entries.iterrows():
288
+ if os.path.exists(row['image_path']):
289
+ st.image(
290
+ row['image_path'],
291
+ width=200,
292
+ caption=(
293
+ f"{row['timestamp'].strftime('%Y-%m-%d %H:%M')} — "
294
+ f"Score: {row['score']:.2f}"
295
+ )
296
+ )
297
+ st.markdown("#### Details")
298
+ st.dataframe(
299
+ entries[
300
+ ['timestamp','geo_location','label','score',
301
+ 'body_location','prior_consultation','pain','itch']
302
+ ]
303
+ .rename(columns={
304
+ 'timestamp':'Time','geo_location':'Location',
305
+ 'label':'Diagnosis','score':'Confidence',
306
+ 'body_location':'Body Part','prior_consultation':'Prior Consult',
307
+ 'pain':'Pain','itch':'Itch'
308
+ })
309
+ .sort_values('Time', ascending=False)
310
+ )
311
+
312
+ else:
313
+ st.header("📂 Dataset Explorer")
314
+ st.write("Preview images from the Harvard Skin Cancer Dataset")
315
+
316
+ # pick up to 15 image files
317
+ image_files = [
318
+ f for f in os.listdir(DATA_DIR)
319
+ if os.path.isfile(os.path.join(DATA_DIR, f))
320
+ and f.lower().endswith((".jpg", ".jpeg", ".png"))
321
+ ][:15]
322
+
323
+ for i in range(0, len(image_files), 3):
324
+ cols = st.columns(3)
325
+ for col, fn in zip(cols, image_files[i : i + 3]):
326
+ path = os.path.join(DATA_DIR, fn)
327
+ img = Image.open(path)
328
+ col.image(img, use_container_width=True)
329
+ col.caption(fn)
330
+
331
+ st.sidebar.markdown("---")
332
+ st.sidebar.write("Dataset powered by Harvard Dataverse [DBW86T]")
333
+ st.sidebar.write(f"Model: {MODEL_NAME}")
334
+ st.sidebar.write(f"LLM: {LLM_NAME}")
335
+
336
+ if __name__ == '__main__':
337
+ st.write()