Pro-Coder commited on
Commit
8253efc
Β·
verified Β·
1 Parent(s): 329d067

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +370 -0
app.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Skin Disease Detection β€” Demo
3
+ ------------------------------
4
+ A Gradio app for Hugging Face Spaces with two tabs:
5
+ 1. Image Diagnosis β€” upload (or pick a test image) and get a classifier
6
+ prediction plus a plain-language, urgency-aware explanation.
7
+ 2. Chat Assistant β€” a multi-turn triage chatbot. It can accept an image,
8
+ asks the kind of follow-up questions a real triage intake would, and
9
+ after enough context gives a preliminary assessment with urgency-tiered
10
+ guidance.
11
+
12
+ IMPORTANT: This remains a research/portfolio project, not a validated
13
+ medical device. It has not been clinically evaluated or regulatory
14
+ cleared. It should never be the sole basis for a health decision β€” that
15
+ framing shows up once, clearly, rather than as a repeated warning block
16
+ after every message, but it's still true and still matters.
17
+ """
18
+
19
+ import os
20
+
21
+ import gradio as gr
22
+ import spaces
23
+ import requests
24
+ from PIL import Image
25
+ from transformers import pipeline
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Config β€” override any of these via Space "Variables and secrets"
29
+ # ---------------------------------------------------------------------------
30
+ IMAGE_MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "Anwarkh1/Skin_Cancer-Image_Classification")
31
+ # Hugging Face retired the old api-inference.huggingface.co Serverless API in
32
+ # favor of the "Inference Providers" router (OpenAI-compatible). Any chat
33
+ # model listed at https://huggingface.co/models?inference_provider=hf-inference
34
+ # works here.
35
+ CHAT_MODEL_ID = os.environ.get("CHAT_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
36
+ HF_TOKEN = os.environ.get("HF_TOKEN") # add as a Space SECRET to enable the chatbot
37
+ ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
38
+
39
+ PAGE_DISCLAIMER = (
40
+ "This tool is a research/portfolio project, not a medical device. It hasn't "
41
+ "been clinically validated. Use it to get informed and organize your thoughts "
42
+ "before a real appointment β€” not as a substitute for one."
43
+ )
44
+
45
+ # Optional second classifier specifically for pigmented-lesion cases (HAM10000-based,
46
+ # where melanoma is its own clean label). Useful because broader taxonomies like
47
+ # DermNet lump "Melanoma Skin Cancer, Nevi and Moles" into one label β€” this lets a
48
+ # mole/nevus-flagged image get a second, more specific opinion. Leave unset to disable.
49
+ LESION_MODEL_ID = os.environ.get("LESION_MODEL_ID", "")
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Urgency tiering β€” keyword-based rather than an exact-match label dict, so it
53
+ # works across different classifier taxonomies (the original 7-class HAM10000
54
+ # labels, the 23-class DermNet labels, or any future swap) without needing to
55
+ # hardcode every exact label string. Checked in priority order.
56
+ # ---------------------------------------------------------------------------
57
+ URGENT_KEYWORDS = [
58
+ "melanoma", "malignant", "carcinoma", "actinic keratos",
59
+ "bullous", "lupus", "systemic", "vasculitis", "cellulitis",
60
+ ]
61
+ PROMPT_DOCTOR_KEYWORDS = [
62
+ "fungal", "fungus", "candidiasis", "tinea", "ringworm",
63
+ "scabies", "lyme", "infestation", "wart", "molluscum",
64
+ "viral", "herpes", "hpv", "std", "exanthem", "drug eruption",
65
+ "impetigo", "bacterial",
66
+ ]
67
+ # Anything not matching the above falls through to "general_care" β€” typically
68
+ # manageable/chronic conditions (acne, eczema, psoriasis, hives, hair loss,
69
+ # benign tumors, common moles, etc.) where general skin-care guidance fits.
70
+
71
+ TIER_LABELS = {
72
+ "urgent": "higher-risk β€” recommend seeing a dermatologist soon",
73
+ "prompt_doctor_visit": "needs a proper diagnosis/prescription β€” recommend seeing a doctor, not urgent-emergency",
74
+ "general_care": "typically manageable β€” general skin-care guidance fits, doctor visit optional",
75
+ }
76
+
77
+
78
+ def classify_tier(label):
79
+ """Map a classifier label to an urgency tier via keyword matching."""
80
+ l = label.lower()
81
+ for kw in URGENT_KEYWORDS:
82
+ if kw in l:
83
+ return "urgent"
84
+ for kw in PROMPT_DOCTOR_KEYWORDS:
85
+ if kw in l:
86
+ return "prompt_doctor_visit"
87
+ return "general_care"
88
+
89
+
90
+ # Friendly one-line descriptions for labels we recognize exactly (both the
91
+ # original 7-class HAM10000 set and common DermNet-style labels). Purely
92
+ # cosmetic β€” if a label isn't here, the tier-based guidance still works fine
93
+ # without a description.
94
+ KNOWN_DESCRIPTIONS = {
95
+ "actinic keratoses": "A rough, scaly patch caused by sun damage.",
96
+ "basal cell carcinoma": "The most common type of skin cancer.",
97
+ "melanoma": "The most serious common type of skin cancer.",
98
+ "benign keratosis-like lesions": "Non-cancerous growths such as seborrheic keratoses or solar lentigines.",
99
+ "dermatofibroma": "A common benign skin nodule, often on the legs.",
100
+ "melanocytic nevi": "Ordinary moles.",
101
+ "vascular lesions": "Blood-vessel-related marks such as angiomas.",
102
+ }
103
+
104
+ SYSTEM_PROMPT = """You are a warm, knowledgeable skin-health triage assistant. You are not a doctor and cannot diagnose anyone β€” but your job is to be genuinely useful, not to hide behind constant disclaimers.
105
+
106
+ CONVERSATION STYLE
107
+ - Have a real back-and-forth. Ask about one or two things at a time, not a long checklist at once.
108
+ - Useful things to learn over the conversation (don't force all of them if the user has already told you, or if it's clearly unnecessary):
109
+ - How long they've had it / when they first noticed it
110
+ - Whether it's changed recently in size, shape, or color
111
+ - Symptoms: itching, bleeding, pain, crusting, oozing, discharge, fever
112
+ - Personal or family history of relevant conditions
113
+ - Relevant exposure history (sun, new products, contacts, travel, bites)
114
+ - Where on the body it is
115
+ - If the user shared an image, you'll also receive the image classifier's findings as extra context, including an urgency tier (not shown verbatim to the user) β€” weave that in naturally rather than reading out raw percentages.
116
+
117
+ GIVING A PRELIMINARY ASSESSMENT
118
+ Once you have enough context (often after 2-5 exchanges, sooner if the user just wants a quick read, or immediately if red flags are already obvious), give a clear preliminary assessment using three tiers:
119
+ - **URGENT** (cancer-related findings, or things like bullous/autoimmune/systemic conditions, cellulitis, vasculitis) OR any red-flag symptoms (rapid growth, irregular/changing borders, multiple colors, asymmetry, a sore that won't heal, bleeding, spreading redness, fever) β€” be direct: recommend seeing a dermatologist or doctor soon, and explain briefly why those signs matter. Don't soften this into vague "keep an eye on it" language. Note: some categories (like a classifier label that groups "melanoma" together with ordinary moles) genuinely can't be told apart by the model β€” when that ambiguity exists, say so plainly and default to recommending it get checked rather than assuming it's benign.
120
+ - **NEEDS A DOCTOR VISIT, NOT URGENT** (infections β€” fungal, viral, bacterial, STD-related, infestations like scabies) β€” explain that these generally need a proper diagnosis and often a prescription to clear up, so a doctor visit is the right next step, but it's not an emergency. For anything STD-related, stay factual and non-judgmental, and emphasize in-person testing rather than guessing from a photo.
121
+ - **TYPICALLY MANAGEABLE** (acne, eczema, psoriasis, hives, hair loss, common moles, benign growths, contact dermatitis, etc.) with no red flags β€” explain what that category usually is, and give general skin-care guidance: gentle skincare habits, sun protection, not picking or scratching, and watching for changes. It's fine to mention a dermatologist visit is a reasonable option too, especially if they're unsure, worried, or it's not improving β€” but don't invent a treatment plan or prescribe anything.
122
+ - Never give specific medications, dosages, or treatment prescriptions β€” general skin-care habits are fine; treating a self- or AI-identified condition with anything beyond general care is not.
123
+ - You don't need to repeat a formal warning block every message. Say once, naturally, as part of your assessment β€” not as a bolted-on disclaimer β€” that this is a preliminary read from a conversation and an image classifier, and that an in-person exam is what actually confirms things. Then move on; don't repeat it every turn.
124
+
125
+ URGENT SITUATIONS
126
+ If the user describes something urgent β€” rapidly growing lesion, uncontrolled bleeding, signs of spreading infection, fever with a skin issue, severe pain β€” tell them clearly to seek in-person or emergency care promptly, regardless of how many turns you've had.
127
+
128
+ Keep replies conversational length β€” a few sentences for a question, a bit longer for the assessment itself."""
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Lazy-loaded models (so the Space boots fast and only loads on first use)
133
+ # ---------------------------------------------------------------------------
134
+ _classifier = None
135
+ _lesion_classifier = None
136
+
137
+
138
+ def get_classifier():
139
+ global _classifier
140
+ if _classifier is None:
141
+ import torch
142
+
143
+ device = 0 if torch.cuda.is_available() else -1
144
+ _classifier = pipeline("image-classification", model=IMAGE_MODEL_ID, device=device)
145
+ return _classifier
146
+
147
+
148
+ def get_lesion_classifier():
149
+ """Optional second opinion model for pigmented-lesion cases. Returns None if disabled."""
150
+ global _lesion_classifier
151
+ if not LESION_MODEL_ID:
152
+ return None
153
+ if _lesion_classifier is None:
154
+ import torch
155
+
156
+ device = 0 if torch.cuda.is_available() else -1
157
+ _lesion_classifier = pipeline("image-classification", model=LESION_MODEL_ID, device=device)
158
+ return _lesion_classifier
159
+
160
+
161
+ def chat_completion(messages, max_tokens=500):
162
+ """Call the Hugging Face Inference Providers router directly (OpenAI-compatible)."""
163
+ if not HF_TOKEN:
164
+ return None
165
+ resp = requests.post(
166
+ ROUTER_URL,
167
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
168
+ json={"model": CHAT_MODEL_ID, "messages": messages, "max_tokens": max_tokens},
169
+ timeout=60,
170
+ )
171
+ resp.raise_for_status()
172
+ data = resp.json()
173
+ return data["choices"][0]["message"]["content"]
174
+
175
+
176
+ def classify_image(image):
177
+ """Run the primary classifier and return (preds, formatted_lines). If the top
178
+ prediction looks like a mixed/ambiguous pigmented-lesion label and a second
179
+ lesion-specific model is configured, also run that for a second opinion."""
180
+ clf = get_classifier()
181
+ preds = clf(image, top_k=5)
182
+ lines = []
183
+ for p in preds:
184
+ label = p["label"]
185
+ score = p["score"] * 100
186
+ desc = KNOWN_DESCRIPTIONS.get(label.lower(), "")
187
+ desc_txt = f" \n _{desc}_" if desc else ""
188
+ lines.append(f"- **{label}** β€” {score:.1f}%{desc_txt}")
189
+
190
+ top_label = preds[0]["label"].lower()
191
+ if ("nevi" in top_label or "mole" in top_label) and "melanoma" in top_label:
192
+ lesion_clf = get_lesion_classifier()
193
+ if lesion_clf is not None:
194
+ lesion_preds = lesion_clf(image, top_k=3)
195
+ lines.append("\n_Second opinion from a lesion-specific model (melanoma is a distinct label here):_")
196
+ for p in lesion_preds:
197
+ lines.append(f"- **{p['label']}** β€” {p['score']*100:.1f}%")
198
+ preds = preds + [{"label": f"[lesion-model] {p['label']}", "score": p["score"]} for p in lesion_preds]
199
+
200
+ return preds, lines
201
+
202
+
203
+ def build_classifier_context(preds):
204
+ """Turn classifier output into a compact context block for the LLM (not shown raw to the user)."""
205
+ parts = []
206
+ for p in preds[:4]:
207
+ label = p["label"]
208
+ if label.startswith("[lesion-model]"):
209
+ # second-opinion predictions: tier by the underlying label, minus the tag
210
+ bare = label.replace("[lesion-model] ", "")
211
+ tier = classify_tier(bare)
212
+ parts.append(f"{label} ({p['score']*100:.1f}%, second-opinion, {tier})")
213
+ continue
214
+ tier = classify_tier(label)
215
+ desc = KNOWN_DESCRIPTIONS.get(label.lower(), "")
216
+ parts.append(f"{label} ({p['score']*100:.1f}%, {tier}{': ' + desc if desc else ''})")
217
+ return "Image classifier findings for your use (do not read these percentages verbatim): " + "; ".join(parts)
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Image diagnosis tab (single-shot: upload -> classify -> explain)
222
+ # ---------------------------------------------------------------------------
223
+ @spaces.GPU
224
+ def diagnose_image(image):
225
+ if image is None:
226
+ return "Please upload an image or pick one of the test images first."
227
+
228
+ try:
229
+ preds, lines_list = classify_image(image)
230
+ except Exception as e:
231
+ return f"**Model error:** {e}\n\nMake sure `IMAGE_MODEL_ID` is a valid image-classification model."
232
+
233
+ lines = ["### πŸ”¬ Classifier prediction\n"] + lines_list
234
+
235
+ if HF_TOKEN:
236
+ context = build_classifier_context(preds)
237
+ prompt = (
238
+ f"{context}\n\n"
239
+ "The user just uploaded a single image with no conversation yet. Give a short "
240
+ "preliminary assessment following your instructions: plain-language explanation of "
241
+ "the top finding, urgency-tiered guidance, and a brief natural mention that an "
242
+ "in-person dermatologist exam is what actually confirms things. Keep it to 4-6 sentences."
243
+ )
244
+ try:
245
+ explanation = chat_completion(
246
+ [
247
+ {"role": "system", "content": SYSTEM_PROMPT},
248
+ {"role": "user", "content": prompt},
249
+ ],
250
+ max_tokens=300,
251
+ )
252
+ lines.append(f"\n### πŸ€– Assessment\n{explanation}")
253
+ except Exception as e:
254
+ lines.append(f"\n_(Assessment unavailable: {e})_")
255
+ else:
256
+ lines.append(
257
+ "\n_Add an `HF_TOKEN` secret to this Space to also get a plain-language "
258
+ "assessment from the chat model here._"
259
+ )
260
+
261
+ lines.append(
262
+ "\n---\n_Tip: use the **Chat Assistant** tab for a fuller triage conversation β€” "
263
+ "it can ask follow-up questions and give a more tailored read._"
264
+ )
265
+ return "\n".join(lines)
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Chat tab β€” multimodal, multi-turn triage
270
+ # ---------------------------------------------------------------------------
271
+ def _extract_text_and_image(message):
272
+ """Normalize gr.ChatInterface(multimodal=True) message input into (text, image_path_or_None)."""
273
+ if isinstance(message, dict):
274
+ text = message.get("text", "") or ""
275
+ files = message.get("files") or []
276
+ image_path = files[0] if files else None
277
+ return text, image_path
278
+ return str(message), None
279
+
280
+
281
+ def chat_respond(message, history):
282
+ if not HF_TOKEN:
283
+ return (
284
+ "Chat isn't configured yet β€” add an `HF_TOKEN` secret to this Space "
285
+ "(Settings β†’ Variables and secrets) to enable the chatbot."
286
+ )
287
+
288
+ text, image_path = _extract_text_and_image(message)
289
+
290
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
291
+ for turn in history:
292
+ if isinstance(turn, dict):
293
+ role = turn.get("role")
294
+ content = turn.get("content")
295
+ if isinstance(content, str):
296
+ messages.append({"role": role, "content": content})
297
+ else:
298
+ user_msg, bot_msg = turn
299
+ if isinstance(user_msg, str):
300
+ messages.append({"role": "user", "content": user_msg})
301
+ if bot_msg:
302
+ messages.append({"role": "assistant", "content": bot_msg})
303
+
304
+ user_content = text
305
+ if image_path:
306
+ try:
307
+ img = Image.open(image_path)
308
+ preds, _ = classify_image(img)
309
+ context = build_classifier_context(preds)
310
+ user_content = f"{context}\n\nUser's message: {text or '(no message, just shared an image)'}"
311
+ except Exception as e:
312
+ user_content = f"(Image analysis failed: {e})\n\nUser's message: {text}"
313
+
314
+ messages.append({"role": "user", "content": user_content})
315
+
316
+ try:
317
+ return chat_completion(messages, max_tokens=500)
318
+ except Exception as e:
319
+ return f"Sorry, I hit an error talking to the model: {e}"
320
+
321
+
322
+ # ---------------------------------------------------------------------------
323
+ # UI
324
+ # ---------------------------------------------------------------------------
325
+ EXAMPLES_DIR = "examples"
326
+ example_images = []
327
+ if os.path.isdir(EXAMPLES_DIR):
328
+ example_images = [
329
+ os.path.join(EXAMPLES_DIR, f)
330
+ for f in sorted(os.listdir(EXAMPLES_DIR))
331
+ if f.lower().endswith((".jpg", ".jpeg", ".png"))
332
+ ]
333
+
334
+ with gr.Blocks(title="Skin Disease Detection β€” Demo") as demo:
335
+ gr.Markdown("# 🩺 Skin Disease Detection")
336
+ gr.Markdown(f"_{PAGE_DISCLAIMER}_")
337
+
338
+ with gr.Tab("πŸ“· Quick Image Check"):
339
+ with gr.Row():
340
+ with gr.Column():
341
+ img_in = gr.Image(type="pil", label="Upload a skin image")
342
+ if example_images:
343
+ gr.Examples(examples=example_images, inputs=img_in, label="Or try a test image")
344
+ else:
345
+ gr.Markdown(
346
+ "_No bundled test images found. Run `scripts/download_examples.py` "
347
+ "before deploying, or just upload your own image._"
348
+ )
349
+ analyze_btn = gr.Button("Analyze image", variant="primary")
350
+ with gr.Column():
351
+ result_md = gr.Markdown()
352
+ analyze_btn.click(diagnose_image, inputs=img_in, outputs=result_md)
353
+
354
+ with gr.Tab("πŸ’¬ Chat Assistant"):
355
+ gr.ChatInterface(
356
+ fn=chat_respond,
357
+ multimodal=True,
358
+ description=(
359
+ "Talk through what you're noticing, and optionally attach a photo (πŸ“Ž). "
360
+ "The assistant will ask a few follow-up questions before giving a preliminary read."
361
+ ),
362
+ )
363
+
364
+ gr.Markdown(
365
+ "---\nBuilt with πŸ€— Transformers + Gradio. "
366
+ f"Image model: `{IMAGE_MODEL_ID}` Β· Chat model: `{CHAT_MODEL_ID}`"
367
+ )
368
+
369
+ if __name__ == "__main__":
370
+ demo.launch()