Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,29 @@
|
|
| 1 |
"""
|
| 2 |
-
Skin Disease Detection β Demo
|
| 3 |
-
------------------------------
|
| 4 |
-
|
| 5 |
-
1. Image
|
| 6 |
-
|
| 7 |
-
2. Chat Assistant β
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
import os
|
|
|
|
|
|
|
| 20 |
|
| 21 |
import gradio as gr
|
| 22 |
import spaces
|
|
@@ -27,33 +34,65 @@ from transformers import pipeline
|
|
| 27 |
# ---------------------------------------------------------------------------
|
| 28 |
# Config β override any of these via Space "Variables and secrets"
|
| 29 |
# ---------------------------------------------------------------------------
|
| 30 |
-
|
| 31 |
-
IMAGE_MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "Pro-Coder/skin-lesion-vit-finetuned")
|
| 32 |
-
# Hugging Face retired the old api-inference.huggingface.co Serverless API in
|
| 33 |
-
# favor of the "Inference Providers" router (OpenAI-compatible). Any chat
|
| 34 |
-
# model listed at https://huggingface.co/models?inference_provider=hf-inference
|
| 35 |
-
# works here.
|
| 36 |
-
CHAT_MODEL_ID = os.environ.get("CHAT_MODEL_ID", "openai/gpt-oss-120b")
|
| 37 |
HF_TOKEN = os.environ.get("HF_TOKEN") # add as a Space SECRET to enable the chatbot
|
|
|
|
| 38 |
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
PAGE_DISCLAIMER = (
|
| 41 |
"This tool is a research/portfolio project, not a medical device. It hasn't "
|
| 42 |
"been clinically validated. Use it to get informed and organize your thoughts "
|
| 43 |
"before a real appointment β not as a substitute for one."
|
| 44 |
)
|
| 45 |
|
| 46 |
-
# Optional second classifier
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
-
# mole/nevus-flagged image get a second, more specific opinion. Leave unset to disable.
|
| 50 |
-
LESION_MODEL_ID = os.environ.get("LESION_MODEL_ID", "")
|
| 51 |
|
| 52 |
# ---------------------------------------------------------------------------
|
| 53 |
-
# Urgency tiering
|
| 54 |
-
# works across different classifier taxonomies (the original 7-class HAM10000
|
| 55 |
-
# labels, the 23-class DermNet labels, or any future swap) without needing to
|
| 56 |
-
# hardcode every exact label string. Checked in priority order.
|
| 57 |
# ---------------------------------------------------------------------------
|
| 58 |
URGENT_KEYWORDS = [
|
| 59 |
"melanoma", "malignant", "carcinoma", "actinic keratos",
|
|
@@ -65,9 +104,6 @@ PROMPT_DOCTOR_KEYWORDS = [
|
|
| 65 |
"viral", "herpes", "hpv", "std", "exanthem", "drug eruption",
|
| 66 |
"impetigo", "bacterial",
|
| 67 |
]
|
| 68 |
-
# Anything not matching the above falls through to "general_care" β typically
|
| 69 |
-
# manageable/chronic conditions (acne, eczema, psoriasis, hives, hair loss,
|
| 70 |
-
# benign tumors, common moles, etc.) where general skin-care guidance fits.
|
| 71 |
|
| 72 |
SEVERITY = {
|
| 73 |
"urgent": {"label": "High", "emoji": "π΄", "note": "recommend seeing a dermatologist/doctor soon"},
|
|
@@ -77,7 +113,6 @@ SEVERITY = {
|
|
| 77 |
|
| 78 |
|
| 79 |
def classify_tier(label):
|
| 80 |
-
"""Map a classifier label to an urgency tier via keyword matching."""
|
| 81 |
l = label.lower()
|
| 82 |
for kw in URGENT_KEYWORDS:
|
| 83 |
if kw in l:
|
|
@@ -89,15 +124,10 @@ def classify_tier(label):
|
|
| 89 |
|
| 90 |
|
| 91 |
def severity_line(label):
|
| 92 |
-
|
| 93 |
-
s = SEVERITY[tier]
|
| 94 |
return f"{s['emoji']} **Severity: {s['label']}** β {s['note']}"
|
| 95 |
|
| 96 |
|
| 97 |
-
# Friendly one-line descriptions for labels we recognize exactly (both the
|
| 98 |
-
# original 7-class HAM10000 set and common DermNet-style labels). Purely
|
| 99 |
-
# cosmetic β if a label isn't here, the tier-based guidance still works fine
|
| 100 |
-
# without a description.
|
| 101 |
KNOWN_DESCRIPTIONS = {
|
| 102 |
"actinic keratoses": "A rough, scaly patch caused by sun damage.",
|
| 103 |
"basal cell carcinoma": "The most common type of skin cancer.",
|
|
@@ -109,7 +139,6 @@ KNOWN_DESCRIPTIONS = {
|
|
| 109 |
}
|
| 110 |
|
| 111 |
SYSTEM_PROMPT = """You are a warm, knowledgeable skin-health triage assistant. You are not a doctor and cannot diagnose anyone with certainty β but your job is to be genuinely useful and specific, not to hide behind vague hedging or constant disclaimers.
|
| 112 |
-
|
| 113 |
CONVERSATION STYLE β GO DEEPER BEFORE ASSESSING
|
| 114 |
Have a real back-and-forth, one or two questions at a time. Aim to gather a fuller picture than a quick glance would give β typically 5-8 exchanges before your assessment, more if the picture is still unclear, fewer only if the user clearly just wants a fast read or red flags are already obvious. Useful ground to cover (skip anything already answered or clearly irrelevant):
|
| 115 |
- Onset: how long they've had it, how it started
|
|
@@ -121,7 +150,6 @@ Have a real back-and-forth, one or two questions at a time. Aim to gather a full
|
|
| 121 |
- Location and distribution on the body
|
| 122 |
The goal of the extra rounds is to genuinely narrow the differential, not to interrogate β keep it conversational, and if the user gives a rich answer that covers several of these at once, don't force redundant questions.
|
| 123 |
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.
|
| 124 |
-
|
| 125 |
GIVING A PRELIMINARY ASSESSMENT
|
| 126 |
Once you have real depth of context, give a clear, specific preliminary assessment:
|
| 127 |
- Name the 1-2 most likely categories given everything discussed, in plain language, and briefly say why (which symptoms/pattern point that way). It's fine β good, even β to be specific about what you think is most likely. What you must NOT do is claim certainty: use "most consistent with" / "this pattern often points to," never "you have X" or "this is definitely X." A real diagnosis needs an in-person exam and sometimes tests (biopsy, culture, bloodwork) that no photo or conversation can replace β say this once, naturally, as part of the assessment, not as a repeated disclaimer.
|
|
@@ -130,15 +158,13 @@ Once you have real depth of context, give a clear, specific preliminary assessme
|
|
| 130 |
- **Medium** = things that need a proper diagnosis and often a prescription to clear up (fungal, viral, bacterial infections, STD-related, infestations like scabies) but aren't emergencies β recommend a doctor visit, explain why self-treatment usually doesn't fully work here. For anything STD-related, stay factual and non-judgmental, and point toward in-person testing rather than guessing from a photo.
|
| 131 |
- **Low** = typically manageable conditions (acne, eczema, psoriasis, hives, hair loss, common moles, benign growths, contact dermatitis) with no red flags β explain what it usually is, and give general skin-care guidance: gentle skincare habits, sun protection, not picking/scratching, watching for changes. Still fine to mention a doctor visit is reasonable if they're unsure, worried, or it's not improving.
|
| 132 |
- 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.
|
| 133 |
-
|
| 134 |
URGENT SITUATIONS
|
| 135 |
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.
|
| 136 |
-
|
| 137 |
Keep replies conversational length β a few sentences for a question, a bit longer for the assessment itself."""
|
| 138 |
|
| 139 |
|
| 140 |
# ---------------------------------------------------------------------------
|
| 141 |
-
# Lazy-loaded
|
| 142 |
# ---------------------------------------------------------------------------
|
| 143 |
_classifier = None
|
| 144 |
_lesion_classifier = None
|
|
@@ -155,7 +181,6 @@ def get_classifier():
|
|
| 155 |
|
| 156 |
|
| 157 |
def get_lesion_classifier():
|
| 158 |
-
"""Optional second opinion model for pigmented-lesion cases. Returns None if disabled."""
|
| 159 |
global _lesion_classifier
|
| 160 |
if not LESION_MODEL_ID:
|
| 161 |
return None
|
|
@@ -167,29 +192,719 @@ def get_lesion_classifier():
|
|
| 167 |
return _lesion_classifier
|
| 168 |
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
if not HF_TOKEN:
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
| 184 |
try:
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
except Exception:
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
|
|
|
|
|
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
def classify_image(image):
|
| 194 |
"""Run the primary classifier and return (preds, formatted_lines). If the top
|
| 195 |
prediction looks like a mixed/ambiguous pigmented-lesion label and a second
|
|
@@ -218,12 +933,10 @@ def classify_image(image):
|
|
| 218 |
|
| 219 |
|
| 220 |
def build_classifier_context(preds):
|
| 221 |
-
"""Turn classifier output into a compact context block for the LLM (not shown raw to the user)."""
|
| 222 |
parts = []
|
| 223 |
for p in preds[:4]:
|
| 224 |
label = p["label"]
|
| 225 |
if label.startswith("[lesion-model]"):
|
| 226 |
-
# second-opinion predictions: tier by the underlying label, minus the tag
|
| 227 |
bare = label.replace("[lesion-model] ", "")
|
| 228 |
tier = classify_tier(bare)
|
| 229 |
parts.append(f"{label} ({p['score']*100:.1f}%, second-opinion, {tier})")
|
|
@@ -234,11 +947,24 @@ def build_classifier_context(preds):
|
|
| 234 |
return "Image classifier findings for your use (do not read these percentages verbatim): " + "; ".join(parts)
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
# ---------------------------------------------------------------------------
|
| 238 |
# Image diagnosis tab (single-shot: upload -> classify -> explain)
|
| 239 |
# ---------------------------------------------------------------------------
|
| 240 |
@spaces.GPU
|
| 241 |
-
def diagnose_image(image):
|
| 242 |
if image is None:
|
| 243 |
return "Please upload an image or pick one of the test images first."
|
| 244 |
|
|
@@ -250,34 +976,33 @@ def diagnose_image(image):
|
|
| 250 |
lines = ["### π¬ Classifier prediction\n"] + lines_list
|
| 251 |
lines.append(f"\n{severity_line(preds[0]['label'])}")
|
| 252 |
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
)
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
{"role": "user", "content": prompt},
|
| 270 |
-
],
|
| 271 |
-
max_tokens=300,
|
| 272 |
-
)
|
| 273 |
-
lines.append(f"\n### π€ Assessment\n{explanation}")
|
| 274 |
-
except Exception as e:
|
| 275 |
-
lines.append(f"\n_(Assessment unavailable: {e})_")
|
| 276 |
-
else:
|
| 277 |
lines.append(
|
| 278 |
-
"
|
| 279 |
-
"
|
| 280 |
)
|
|
|
|
|
|
|
| 281 |
|
| 282 |
lines.append(
|
| 283 |
"\n---\n_Tip: use the **Chat Assistant** tab for a fuller triage conversation β "
|
|
@@ -289,15 +1014,12 @@ def diagnose_image(image):
|
|
| 289 |
# ---------------------------------------------------------------------------
|
| 290 |
# Chat tab β multimodal, multi-turn triage
|
| 291 |
# ---------------------------------------------------------------------------
|
| 292 |
-
MIN_ROUNDS_BEFORE_ASSESSMENT = 4 # user turns, not counting the current one
|
| 293 |
-
|
| 294 |
-
|
| 295 |
def _extract_text_and_image(message):
|
| 296 |
-
"""Normalize gr.ChatInterface(multimodal=True) message input into (text, image_path_or_None)."""
|
| 297 |
if isinstance(message, dict):
|
| 298 |
text = message.get("text", "") or ""
|
| 299 |
files = message.get("files") or []
|
| 300 |
-
|
|
|
|
| 301 |
return text, image_path
|
| 302 |
return str(message), None
|
| 303 |
|
|
@@ -307,9 +1029,6 @@ def _count_user_turns(messages):
|
|
| 307 |
|
| 308 |
|
| 309 |
def _stage_note(user_turn_count):
|
| 310 |
-
"""Injected each turn so multi-round behavior is enforced by code, not just
|
| 311 |
-
requested once in the system prompt β the model gets a fresh reminder of
|
| 312 |
-
what stage the conversation is in on every single call."""
|
| 313 |
if user_turn_count < MIN_ROUNDS_BEFORE_ASSESSMENT:
|
| 314 |
return (
|
| 315 |
f"[Internal note β not from the user: this is exchange {user_turn_count} of at least "
|
|
@@ -327,48 +1046,110 @@ def _stage_note(user_turn_count):
|
|
| 327 |
)
|
| 328 |
|
| 329 |
|
| 330 |
-
|
| 331 |
-
if not HF_TOKEN:
|
| 332 |
-
return (
|
| 333 |
-
"Chat isn't configured yet β add an `HF_TOKEN` secret to this Space "
|
| 334 |
-
"(Settings β Variables and secrets) to enable the chatbot."
|
| 335 |
-
)
|
| 336 |
|
| 337 |
-
text, image_path = _extract_text_and_image(message)
|
| 338 |
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
| 341 |
if isinstance(turn, dict):
|
| 342 |
-
role = turn.get("role")
|
| 343 |
-
content
|
| 344 |
-
|
| 345 |
-
|
|
|
|
| 346 |
else:
|
| 347 |
-
|
| 348 |
-
if isinstance(
|
| 349 |
-
|
| 350 |
-
if
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
-
|
|
|
|
| 354 |
if image_path:
|
| 355 |
try:
|
| 356 |
-
|
| 357 |
-
preds, _ = classify_image(img)
|
| 358 |
-
context = build_classifier_context(preds)
|
| 359 |
-
user_content = f"{context}\n\nUser's message: {text or '(no message, just shared an image)'}"
|
| 360 |
except Exception as e:
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
-
# current turn counts too, since the model is about to respond to it
|
| 364 |
current_turn_count = _count_user_turns(messages) + 1
|
| 365 |
-
|
| 366 |
-
messages.append({"role": "user", "content": f"{stage_note}\n\n{user_content}"})
|
| 367 |
|
| 368 |
try:
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
|
| 374 |
# ---------------------------------------------------------------------------
|
|
@@ -377,28 +1158,17 @@ def chat_respond(message, history):
|
|
| 377 |
ASSETS_DIR = "assets"
|
| 378 |
|
| 379 |
|
| 380 |
-
|
| 381 |
-
|
| 382 |
def load_performance_reports():
|
| 383 |
-
"""Scan assets/ for
|
| 384 |
-
|
| 385 |
-
and any other same-prefix analysis images (threshold curves, cluster
|
| 386 |
-
breakdowns, etc.).
|
| 387 |
-
2. Image-only reports: any *_confusion_matrix.{png,jpg,jpeg} that doesn't
|
| 388 |
-
have a matching metrics.json yet -- shown with its charts but no
|
| 389 |
-
numeric table, so you don't have to wait on exporting metrics.json
|
| 390 |
-
just to see the images you already generated.
|
| 391 |
-
Returns a list of dicts; empty list if nothing's been uploaded at all.
|
| 392 |
-
"""
|
| 393 |
import json
|
| 394 |
-
|
| 395 |
reports = []
|
| 396 |
if not os.path.isdir(ASSETS_DIR):
|
| 397 |
return reports
|
| 398 |
all_files = sorted(os.listdir(ASSETS_DIR))
|
| 399 |
-
claimed = set()
|
| 400 |
-
|
| 401 |
-
# --- Pass 1: full reports (metrics.json + its images) ---
|
| 402 |
for fname in all_files:
|
| 403 |
if not fname.endswith("_metrics.json"):
|
| 404 |
continue
|
|
@@ -408,7 +1178,7 @@ def load_performance_reports():
|
|
| 408 |
data = json.load(f)
|
| 409 |
except Exception:
|
| 410 |
continue
|
| 411 |
-
|
| 412 |
image_path = None
|
| 413 |
for ext in (".png", ".jpg", ".jpeg"):
|
| 414 |
candidate = os.path.join(ASSETS_DIR, f"{prefix}_confusion_matrix{ext}")
|
|
@@ -416,7 +1186,7 @@ def load_performance_reports():
|
|
| 416 |
image_path = candidate
|
| 417 |
claimed.add(f"{prefix}_confusion_matrix{ext}")
|
| 418 |
break
|
| 419 |
-
|
| 420 |
extra_images = []
|
| 421 |
for other in all_files:
|
| 422 |
if not other.startswith(prefix + "_") or not other.lower().endswith((".png", ".jpg", ".jpeg")):
|
|
@@ -426,24 +1196,21 @@ def load_performance_reports():
|
|
| 426 |
label = other[len(prefix) + 1:].rsplit(".", 1)[0].replace("_", " ").strip().title()
|
| 427 |
extra_images.append({"path": os.path.join(ASSETS_DIR, other), "label": label})
|
| 428 |
claimed.add(other)
|
| 429 |
-
|
| 430 |
reports.append({"data": data, "image_path": image_path, "extra_images": extra_images})
|
| 431 |
-
|
| 432 |
-
# --- Pass 2: image-only reports -- any confusion-matrix image not already
|
| 433 |
-
# claimed by a full report above, grouped with its same-prefix siblings ---
|
| 434 |
seen_prefixes = set()
|
| 435 |
for fname in all_files:
|
| 436 |
if fname in claimed or not fname.lower().endswith((".png", ".jpg", ".jpeg")):
|
| 437 |
continue
|
| 438 |
-
|
| 439 |
-
idx = fname.lower().find(marker)
|
| 440 |
if idx == -1:
|
| 441 |
-
continue
|
| 442 |
prefix = fname[:idx]
|
| 443 |
if prefix in seen_prefixes:
|
| 444 |
continue
|
| 445 |
seen_prefixes.add(prefix)
|
| 446 |
-
|
| 447 |
extra_images = []
|
| 448 |
for other in all_files:
|
| 449 |
if other == fname or other in claimed or not other.startswith(prefix + "_"):
|
|
@@ -453,34 +1220,32 @@ def load_performance_reports():
|
|
| 453 |
label = other[len(prefix) + 1:].rsplit(".", 1)[0].replace("_", " ").strip().title()
|
| 454 |
extra_images.append({"path": os.path.join(ASSETS_DIR, other), "label": label})
|
| 455 |
claimed.add(other)
|
| 456 |
-
|
| 457 |
-
model_name = prefix.replace("_", " ").strip().title() or "Model"
|
| 458 |
reports.append({
|
| 459 |
-
"data": {"model_name":
|
| 460 |
"image_path": os.path.join(ASSETS_DIR, fname),
|
| 461 |
"extra_images": extra_images,
|
| 462 |
})
|
| 463 |
-
|
| 464 |
-
return reports
|
| 465 |
|
|
|
|
| 466 |
|
| 467 |
|
| 468 |
def format_performance_markdown(report):
|
| 469 |
data = report["data"]
|
| 470 |
lines = [f"### {data.get('model_name', 'Model')}"]
|
| 471 |
-
|
| 472 |
if data.get("image_only"):
|
| 473 |
lines.append(
|
| 474 |
"_Charts available β metrics summary not uploaded yet. Add a matching "
|
| 475 |
"`*_metrics.json` to this prefix for the full accuracy/F1/per-class table._"
|
| 476 |
)
|
| 477 |
return "\n".join(lines)
|
| 478 |
-
|
| 479 |
acc = data.get("accuracy")
|
| 480 |
f1m = data.get("f1_macro")
|
| 481 |
if acc is not None:
|
| 482 |
lines.append(f"**Accuracy:** {acc*100:.1f}% Β· **Macro F1:** {f1m*100:.1f}%" if f1m is not None else f"**Accuracy:** {acc*100:.1f}%")
|
| 483 |
-
|
| 484 |
per_class = data.get("per_class", {})
|
| 485 |
if per_class:
|
| 486 |
lines.append("\n| Class | Precision | Recall | F1 | Support |")
|
|
@@ -490,20 +1255,19 @@ def format_performance_markdown(report):
|
|
| 490 |
f"| {cls} | {m.get('precision', 0)*100:.1f}% | {m.get('recall', 0)*100:.1f}% "
|
| 491 |
f"| {m.get('f1', 0)*100:.1f}% | {int(m.get('support', 0))} |"
|
| 492 |
)
|
| 493 |
-
|
| 494 |
notes = data.get("notes")
|
| 495 |
if notes:
|
| 496 |
lines.append(f"\n_Note: {notes}_")
|
| 497 |
-
|
| 498 |
return "\n".join(lines)
|
| 499 |
|
|
|
|
| 500 |
ABOUT_MARKDOWN = f"""
|
| 501 |
## About this project
|
| 502 |
-
|
| 503 |
A research/portfolio demo exploring how far an image classifier + LLM chat
|
| 504 |
assistant can go toward useful skin-condition triage β while being explicit
|
| 505 |
about what it isn't: a validated medical device.
|
| 506 |
-
|
| 507 |
### What's inside
|
| 508 |
- **Quick Image Check** β upload a photo, get a classifier prediction plus
|
| 509 |
an LLM-generated plain-language assessment with an explicit Low/Medium/High
|
|
@@ -512,21 +1276,20 @@ about what it isn't: a validated medical device.
|
|
| 512 |
evolution, symptoms, triggers, and history before giving a more targeted
|
| 513 |
preliminary read than a single photo alone could support.
|
| 514 |
- **Model Performance** β the actual test-set metrics for whichever
|
| 515 |
-
fine-tuned model(s) are currently backing this app
|
| 516 |
-
claims about accuracy.
|
| 517 |
-
|
| 518 |
### Models
|
| 519 |
-
- **Image classifier:** configurable via
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
|
|
|
| 530 |
### Severity levels
|
| 531 |
- π΄ **High** β cancer-related, ambiguous-but-could-be-serious, systemic/
|
| 532 |
autoimmune, or red-flag symptoms present. See a doctor soon.
|
|
@@ -534,19 +1297,15 @@ about what it isn't: a validated medical device.
|
|
| 534 |
(infections, infestations). See a doctor, not an emergency.
|
| 535 |
- π’ **Low** β typically manageable with general skin care. Doctor visit
|
| 536 |
optional, especially if unsure or it's not improving.
|
| 537 |
-
|
| 538 |
-
### Known limitations (read this before trusting the output)
|
| 539 |
- **Not clinically validated.** Benchmark accuracy on a public dataset is
|
| 540 |
not the same as real-world diagnostic reliability.
|
| 541 |
-
- **Dataset label limitations.**
|
| 542 |
-
|
| 543 |
-
to High severity rather than pretending to distinguish them.
|
| 544 |
- **Skin-tone representation.** Public dermatology datasets skew toward
|
| 545 |
-
lighter skin tones; performance
|
| 546 |
-
unverified without a dedicated bias audit.
|
| 547 |
- **No clinical validation, IRB review, or regulatory clearance** has been
|
| 548 |
done. This should inform, not replace, professional care.
|
| 549 |
-
|
| 550 |
{PAGE_DISCLAIMER}
|
| 551 |
"""
|
| 552 |
|
|
@@ -567,6 +1326,16 @@ with gr.Blocks(title="Skin Disease Detection β Demo") as demo:
|
|
| 567 |
gr.Markdown("# π©Ί Skin Disease Detection")
|
| 568 |
gr.Markdown(f"_{PAGE_DISCLAIMER}_")
|
| 569 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
with gr.Tab("π· Quick Image Check"):
|
| 571 |
with gr.Row():
|
| 572 |
with gr.Column():
|
|
@@ -581,12 +1350,13 @@ with gr.Blocks(title="Skin Disease Detection β Demo") as demo:
|
|
| 581 |
analyze_btn = gr.Button("Analyze image", variant="primary")
|
| 582 |
with gr.Column():
|
| 583 |
result_md = gr.Markdown()
|
| 584 |
-
analyze_btn.click(diagnose_image, inputs=img_in, outputs=result_md)
|
| 585 |
|
| 586 |
with gr.Tab("π¬ Chat Assistant"):
|
| 587 |
gr.ChatInterface(
|
| 588 |
fn=chat_respond,
|
| 589 |
multimodal=True,
|
|
|
|
| 590 |
description=(
|
| 591 |
"Talk through what you're noticing, and optionally attach a photo (π). "
|
| 592 |
"The assistant will ask several follow-up questions before giving a preliminary "
|
|
@@ -618,8 +1388,8 @@ with gr.Blocks(title="Skin Disease Detection β Demo") as demo:
|
|
| 618 |
|
| 619 |
gr.Markdown(
|
| 620 |
"---\nBuilt with π€ Transformers + Gradio. "
|
| 621 |
-
f"Image model: `{IMAGE_MODEL_ID}` Β·
|
| 622 |
)
|
| 623 |
|
| 624 |
if __name__ == "__main__":
|
| 625 |
-
demo.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
+
Skin Disease Detection β Demo (English-only, multi-model chat + offline assistant)
|
| 3 |
+
-----------------------------------------------------------------------------
|
| 4 |
+
Tabs:
|
| 5 |
+
1. Quick Image Check β upload a photo, get a classifier prediction plus a
|
| 6 |
+
plain-language, urgency-aware assessment with Low/Medium/High severity.
|
| 7 |
+
2. Chat Assistant β multi-round triage chat (optionally with a photo).
|
| 8 |
+
3. Model Performance β metrics/graphs from assets/.
|
| 9 |
+
4. About.
|
| 10 |
+
|
| 11 |
+
Chat-model resilience (new):
|
| 12 |
+
* You can SELECT several chat models (multi-select dropdown). They are tried
|
| 13 |
+
in the order listed. If one fails (not supported, timeout, 5xx, rate limit,
|
| 14 |
+
empty answer) the app silently moves to the next.
|
| 15 |
+
* If EVERY model fails, the app switches to an OFFLINE ASSISTANT: a built-in
|
| 16 |
+
rule-based triage engine that needs no network and no LLM. It asks the same
|
| 17 |
+
kind of structured follow-up questions, matches symptoms against a built-in
|
| 18 |
+
knowledge base of ~30 skin conditions, folds in the image classifier's
|
| 19 |
+
result, and always ends with a Low / Medium / High severity call.
|
| 20 |
+
|
| 21 |
+
IMPORTANT: research/portfolio project, not a validated medical device.
|
| 22 |
"""
|
| 23 |
|
| 24 |
import os
|
| 25 |
+
import re
|
| 26 |
+
import time
|
| 27 |
|
| 28 |
import gradio as gr
|
| 29 |
import spaces
|
|
|
|
| 34 |
# ---------------------------------------------------------------------------
|
| 35 |
# Config β override any of these via Space "Variables and secrets"
|
| 36 |
# ---------------------------------------------------------------------------
|
| 37 |
+
IMAGE_MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "Pro-Coder/skin-lesion-vit-finetuned").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
HF_TOKEN = os.environ.get("HF_TOKEN") # add as a Space SECRET to enable the chatbot
|
| 39 |
+
HF_TOKEN = HF_TOKEN.strip() if HF_TOKEN else HF_TOKEN
|
| 40 |
ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 41 |
|
| 42 |
+
|
| 43 |
+
def _split_models(s):
|
| 44 |
+
return [m.strip() for m in (s or "").split(",") if m.strip()]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _dedupe(seq):
|
| 48 |
+
seen, out = set(), []
|
| 49 |
+
for x in seq:
|
| 50 |
+
if x and x not in seen:
|
| 51 |
+
seen.add(x)
|
| 52 |
+
out.append(x)
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Models offered in the dropdown, in default priority order. Providers rotate
|
| 57 |
+
# their catalogs, so which of these work depends on the providers enabled on
|
| 58 |
+
# your HF account β that's exactly why several are listed.
|
| 59 |
+
# Override with a comma-separated CHAT_MODELS variable. CHAT_MODEL_ID (the old
|
| 60 |
+
# single-model variable) is still honoured and is put first if set.
|
| 61 |
+
# (mistralai/Mistral-7B-Instruct-v0.3 is deliberately absent: confirmed "not a
|
| 62 |
+
# chat model" on the router.)
|
| 63 |
+
_DEFAULT_CHAT_MODELS = (
|
| 64 |
+
"openai/gpt-oss-120b,"
|
| 65 |
+
"openai/gpt-oss-20b,"
|
| 66 |
+
"deepseek-ai/DeepSeek-V3-0324,"
|
| 67 |
+
"meta-llama/Llama-3.3-70B-Instruct,"
|
| 68 |
+
"meta-llama/Llama-3.1-8B-Instruct,"
|
| 69 |
+
"Qwen/Qwen2.5-72B-Instruct,"
|
| 70 |
+
"Qwen/Qwen2.5-7B-Instruct"
|
| 71 |
+
)
|
| 72 |
+
CHAT_MODELS = _dedupe(
|
| 73 |
+
_split_models(os.environ.get("CHAT_MODEL_ID", ""))
|
| 74 |
+
+ _split_models(os.environ.get("CHAT_MODELS", _DEFAULT_CHAT_MODELS))
|
| 75 |
+
)
|
| 76 |
+
CHAT_MODEL_ID = CHAT_MODELS[0] if CHAT_MODELS else ""
|
| 77 |
+
|
| 78 |
+
# A model that hangs shouldn't freeze the chat: cap each attempt, and cap the
|
| 79 |
+
# whole switching chain so the user never waits minutes before the offline
|
| 80 |
+
# assistant takes over.
|
| 81 |
+
CHAT_PER_MODEL_TIMEOUT = int(os.environ.get("CHAT_PER_MODEL_TIMEOUT", "30"))
|
| 82 |
+
CHAT_TOTAL_TIMEOUT = int(os.environ.get("CHAT_TOTAL_TIMEOUT", "90"))
|
| 83 |
+
|
| 84 |
PAGE_DISCLAIMER = (
|
| 85 |
"This tool is a research/portfolio project, not a medical device. It hasn't "
|
| 86 |
"been clinically validated. Use it to get informed and organize your thoughts "
|
| 87 |
"before a real appointment β not as a substitute for one."
|
| 88 |
)
|
| 89 |
|
| 90 |
+
# Optional second classifier for pigmented-lesion cases (HAM10000-based, where
|
| 91 |
+
# melanoma is its own clean label). Leave unset to disable.
|
| 92 |
+
LESION_MODEL_ID = os.environ.get("LESION_MODEL_ID", "").strip()
|
|
|
|
|
|
|
| 93 |
|
| 94 |
# ---------------------------------------------------------------------------
|
| 95 |
+
# Urgency tiering (keyword-based so it works across classifier taxonomies)
|
|
|
|
|
|
|
|
|
|
| 96 |
# ---------------------------------------------------------------------------
|
| 97 |
URGENT_KEYWORDS = [
|
| 98 |
"melanoma", "malignant", "carcinoma", "actinic keratos",
|
|
|
|
| 104 |
"viral", "herpes", "hpv", "std", "exanthem", "drug eruption",
|
| 105 |
"impetigo", "bacterial",
|
| 106 |
]
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
SEVERITY = {
|
| 109 |
"urgent": {"label": "High", "emoji": "π΄", "note": "recommend seeing a dermatologist/doctor soon"},
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
def classify_tier(label):
|
|
|
|
| 116 |
l = label.lower()
|
| 117 |
for kw in URGENT_KEYWORDS:
|
| 118 |
if kw in l:
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
def severity_line(label):
|
| 127 |
+
s = SEVERITY[classify_tier(label)]
|
|
|
|
| 128 |
return f"{s['emoji']} **Severity: {s['label']}** β {s['note']}"
|
| 129 |
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
KNOWN_DESCRIPTIONS = {
|
| 132 |
"actinic keratoses": "A rough, scaly patch caused by sun damage.",
|
| 133 |
"basal cell carcinoma": "The most common type of skin cancer.",
|
|
|
|
| 139 |
}
|
| 140 |
|
| 141 |
SYSTEM_PROMPT = """You are a warm, knowledgeable skin-health triage assistant. You are not a doctor and cannot diagnose anyone with certainty β but your job is to be genuinely useful and specific, not to hide behind vague hedging or constant disclaimers.
|
|
|
|
| 142 |
CONVERSATION STYLE β GO DEEPER BEFORE ASSESSING
|
| 143 |
Have a real back-and-forth, one or two questions at a time. Aim to gather a fuller picture than a quick glance would give β typically 5-8 exchanges before your assessment, more if the picture is still unclear, fewer only if the user clearly just wants a fast read or red flags are already obvious. Useful ground to cover (skip anything already answered or clearly irrelevant):
|
| 144 |
- Onset: how long they've had it, how it started
|
|
|
|
| 150 |
- Location and distribution on the body
|
| 151 |
The goal of the extra rounds is to genuinely narrow the differential, not to interrogate β keep it conversational, and if the user gives a rich answer that covers several of these at once, don't force redundant questions.
|
| 152 |
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.
|
|
|
|
| 153 |
GIVING A PRELIMINARY ASSESSMENT
|
| 154 |
Once you have real depth of context, give a clear, specific preliminary assessment:
|
| 155 |
- Name the 1-2 most likely categories given everything discussed, in plain language, and briefly say why (which symptoms/pattern point that way). It's fine β good, even β to be specific about what you think is most likely. What you must NOT do is claim certainty: use "most consistent with" / "this pattern often points to," never "you have X" or "this is definitely X." A real diagnosis needs an in-person exam and sometimes tests (biopsy, culture, bloodwork) that no photo or conversation can replace β say this once, naturally, as part of the assessment, not as a repeated disclaimer.
|
|
|
|
| 158 |
- **Medium** = things that need a proper diagnosis and often a prescription to clear up (fungal, viral, bacterial infections, STD-related, infestations like scabies) but aren't emergencies β recommend a doctor visit, explain why self-treatment usually doesn't fully work here. For anything STD-related, stay factual and non-judgmental, and point toward in-person testing rather than guessing from a photo.
|
| 159 |
- **Low** = typically manageable conditions (acne, eczema, psoriasis, hives, hair loss, common moles, benign growths, contact dermatitis) with no red flags β explain what it usually is, and give general skin-care guidance: gentle skincare habits, sun protection, not picking/scratching, watching for changes. Still fine to mention a doctor visit is reasonable if they're unsure, worried, or it's not improving.
|
| 160 |
- 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.
|
|
|
|
| 161 |
URGENT SITUATIONS
|
| 162 |
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.
|
|
|
|
| 163 |
Keep replies conversational length β a few sentences for a question, a bit longer for the assessment itself."""
|
| 164 |
|
| 165 |
|
| 166 |
# ---------------------------------------------------------------------------
|
| 167 |
+
# Lazy-loaded image models
|
| 168 |
# ---------------------------------------------------------------------------
|
| 169 |
_classifier = None
|
| 170 |
_lesion_classifier = None
|
|
|
|
| 181 |
|
| 182 |
|
| 183 |
def get_lesion_classifier():
|
|
|
|
| 184 |
global _lesion_classifier
|
| 185 |
if not LESION_MODEL_ID:
|
| 186 |
return None
|
|
|
|
| 192 |
return _lesion_classifier
|
| 193 |
|
| 194 |
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
# Multi-model chat completion with automatic switching
|
| 197 |
+
# ---------------------------------------------------------------------------
|
| 198 |
+
class AllModelsFailed(RuntimeError):
|
| 199 |
+
"""Raised when every selected chat model failed. `.attempts` is a list of
|
| 200 |
+
(model_id, short_reason) so the UI can show what happened."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, attempts):
|
| 203 |
+
self.attempts = attempts
|
| 204 |
+
super().__init__("; ".join(f"{m}: {r}" for m, r in attempts) or "no chat model available")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _error_reason(resp):
|
| 208 |
+
try:
|
| 209 |
+
j = resp.json()
|
| 210 |
+
err = j.get("error", j)
|
| 211 |
+
if isinstance(err, dict):
|
| 212 |
+
msg = err.get("message") or err.get("code") or str(err)
|
| 213 |
+
else:
|
| 214 |
+
msg = str(err)
|
| 215 |
+
except Exception:
|
| 216 |
+
msg = resp.text
|
| 217 |
+
return f"HTTP {resp.status_code}: {str(msg)[:140]}"
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _clean_selection(models):
|
| 221 |
+
if isinstance(models, str):
|
| 222 |
+
models = [models]
|
| 223 |
+
models = _dedupe([str(m).strip() for m in (models or []) if m and str(m).strip()])
|
| 224 |
+
return models or list(CHAT_MODELS)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def chat_completion(messages, max_tokens=500, models=None):
|
| 228 |
+
"""Try each model in `models` (priority order) until one answers.
|
| 229 |
+
|
| 230 |
+
Returns (text, model_used). Raises AllModelsFailed if none worked.
|
| 231 |
+
Every failure type moves on to the next model: unsupported model, timeout,
|
| 232 |
+
network error, rate limit, 5xx, malformed or empty answer. The only
|
| 233 |
+
exception is a 401/403 auth failure, which would fail identically for every
|
| 234 |
+
model, so the chain stops immediately instead of wasting time.
|
| 235 |
+
"""
|
| 236 |
if not HF_TOKEN:
|
| 237 |
+
raise AllModelsFailed([("(none)", "HF_TOKEN is not set")])
|
| 238 |
+
|
| 239 |
+
candidates = _clean_selection(models)
|
| 240 |
+
attempts = []
|
| 241 |
+
started = time.time()
|
| 242 |
+
|
| 243 |
+
for model_id in candidates:
|
| 244 |
+
remaining = CHAT_TOTAL_TIMEOUT - (time.time() - started)
|
| 245 |
+
if remaining <= 2:
|
| 246 |
+
attempts.append((model_id, "skipped (overall time budget used up)"))
|
| 247 |
+
continue
|
| 248 |
+
# gpt-oss models spend hidden "reasoning" tokens first; give them room
|
| 249 |
+
mt = max_tokens * 2 if "gpt-oss" in model_id.lower() else max_tokens
|
| 250 |
try:
|
| 251 |
+
resp = requests.post(
|
| 252 |
+
ROUTER_URL,
|
| 253 |
+
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 254 |
+
json={"model": model_id, "messages": messages, "max_tokens": mt},
|
| 255 |
+
timeout=min(CHAT_PER_MODEL_TIMEOUT, remaining),
|
| 256 |
+
)
|
| 257 |
+
except requests.Timeout:
|
| 258 |
+
attempts.append((model_id, "timed out"))
|
| 259 |
+
continue
|
| 260 |
+
except requests.RequestException as e:
|
| 261 |
+
attempts.append((model_id, f"network error: {str(e)[:100]}"))
|
| 262 |
+
continue
|
| 263 |
+
|
| 264 |
+
if resp.status_code in (401, 403):
|
| 265 |
+
attempts.append((model_id, _error_reason(resp)))
|
| 266 |
+
break # token problem: every model would fail the same way
|
| 267 |
+
|
| 268 |
+
if not resp.ok:
|
| 269 |
+
attempts.append((model_id, _error_reason(resp)))
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
text = (resp.json()["choices"][0]["message"].get("content") or "").strip()
|
| 274 |
except Exception:
|
| 275 |
+
text = ""
|
| 276 |
+
if not text:
|
| 277 |
+
attempts.append((model_id, "empty answer"))
|
| 278 |
+
continue
|
| 279 |
+
return text, model_id
|
| 280 |
+
|
| 281 |
+
raise AllModelsFailed(attempts)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _attempts_note(attempts):
|
| 285 |
+
if not attempts:
|
| 286 |
+
return ""
|
| 287 |
+
return "; ".join(f"`{m}` β {r}" for m, r in attempts)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
_FOOTER_RE = re.compile(r"\n*<sub>.*?</sub>\s*$", re.S)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _strip_footer(text):
|
| 294 |
+
"""Remove the small 'answered by β¦' footer before re-sending history to a model."""
|
| 295 |
+
return _FOOTER_RE.sub("", text or "").strip()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# ===========================================================================
|
| 299 |
+
# OFFLINE ASSISTANT β used only when EVERY selected chat model has failed.
|
| 300 |
+
#
|
| 301 |
+
# Honest scope: this is a rule-based triage engine, not a language model. It
|
| 302 |
+
# cannot understand arbitrary free text the way an LLM can. What it does do,
|
| 303 |
+
# deterministically and with no network:
|
| 304 |
+
# * matches your wording against symptom patterns (negation-aware: "no
|
| 305 |
+
# itching" does not count as itching) for ~30 skin conditions,
|
| 306 |
+
# * blends that with the image classifier's result when a photo was shared,
|
| 307 |
+
# * detects red flags / emergencies and always errs toward the HIGHER
|
| 308 |
+
# severity when unsure,
|
| 309 |
+
# * runs the same multi-round question flow, then gives a named
|
| 310 |
+
# "most consistent with" assessment with Low / Medium / High severity,
|
| 311 |
+
# the same rules the LLM prompt uses.
|
| 312 |
+
# ===========================================================================
|
| 313 |
+
MIN_ROUNDS_BEFORE_ASSESSMENT = 4 # user turns before a full assessment (LLM and offline)
|
| 314 |
+
|
| 315 |
+
TIER_RANK = {"general_care": 0, "prompt_doctor_visit": 1, "urgent": 2}
|
| 316 |
+
RANK_TIER = {0: "general_care", 1: "prompt_doctor_visit", 2: "urgent"}
|
| 317 |
+
RANK_NAME = {0: "Low", 1: "Medium", 2: "High"}
|
| 318 |
+
RANK_EMOJI = {0: "π’", 1: "π‘", 2: "π΄"}
|
| 319 |
+
RANK_NEXT = {
|
| 320 |
+
0: "Usually manageable with general skin care; a doctor visit is optional but reasonable if you're unsure, worried, or it isn't improving.",
|
| 321 |
+
1: "This kind of problem usually needs a proper diagnosis and often a prescription, so a doctor visit is recommended (not an emergency).",
|
| 322 |
+
2: "Please see a dermatologist or doctor soon, directly, without waiting to see whether it settles on its own.",
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
# key: (display name, rank, one-line description, general-care/next-step line)
|
| 326 |
+
CONDITION_KB = {
|
| 327 |
+
"acne": ("acne (or an acne-like condition such as rosacea)", 0,
|
| 328 |
+
"clogged, inflamed pores β pimples, blackheads, sometimes deeper tender bumps",
|
| 329 |
+
"wash gently twice a day, avoid picking or squeezing, use non-comedogenic products and sunscreen"),
|
| 330 |
+
"eczema": ("eczema (atopic dermatitis)", 0,
|
| 331 |
+
"dry, itchy, inflamed skin that flares and settles, often in skin folds",
|
| 332 |
+
"moisturise generously and often, avoid harsh soaps and known triggers, keep nails short and avoid scratching"),
|
| 333 |
+
"psoriasis": ("psoriasis", 0,
|
| 334 |
+
"well-defined, thick, silvery-scaly plaques, often on elbows, knees or scalp",
|
| 335 |
+
"moisturise, avoid scratching or picking scales, manage stress, and get modest sun in moderation"),
|
| 336 |
+
"contact": ("contact dermatitis (a reaction to something that touched the skin)", 0,
|
| 337 |
+
"an itchy or burning rash where the skin met an irritant or allergen",
|
| 338 |
+
"stop using the suspected product, rinse the area with lukewarm water, moisturise, and avoid scratching"),
|
| 339 |
+
"urticaria": ("urticaria (hives)", 0,
|
| 340 |
+
"raised, very itchy welts that come and go within hours",
|
| 341 |
+
"avoid known triggers, wear loose clothing, and keep the skin cool"),
|
| 342 |
+
"seb_derm": ("seborrheic dermatitis", 0,
|
| 343 |
+
"greasy, flaky, pink patches on the scalp, eyebrows, sides of the nose or chest",
|
| 344 |
+
"gentle regular washing of the area and avoiding harsh scrubbing"),
|
| 345 |
+
"alopecia": ("hair loss (alopecia)", 0,
|
| 346 |
+
"thinning hair or patches of hair loss",
|
| 347 |
+
"be gentle with the hair and scalp, avoid tight styles, and note timing and any recent stress or illness"),
|
| 348 |
+
"pigment": ("a pigment disorder (such as vitiligo or melasma)", 0,
|
| 349 |
+
"patches that are lighter or darker than the surrounding skin",
|
| 350 |
+
"daily sunscreen and sun avoidance, which matter for almost all pigment changes"),
|
| 351 |
+
"vascular": ("a vascular lesion (such as a cherry angioma)", 0,
|
| 352 |
+
"a small red or purple blood-vessel growth, usually harmless",
|
| 353 |
+
"no home care is needed; mention it if it bleeds or changes"),
|
| 354 |
+
"bkl": ("a benign keratosis-type growth (such as a seborrheic keratosis)", 0,
|
| 355 |
+
"a waxy, stuck-on, brown or tan growth that is non-cancerous",
|
| 356 |
+
"don't pick at it; see someone if it bleeds, itches or changes quickly"),
|
| 357 |
+
"dermatofibroma": ("a dermatofibroma", 0,
|
| 358 |
+
"a firm, small, brownish benign nodule, often on the legs",
|
| 359 |
+
"no treatment is needed; get it checked if it grows or changes"),
|
| 360 |
+
"nevus": ("an ordinary mole (melanocytic nevus)", 0,
|
| 361 |
+
"a stable, evenly coloured, round spot present for years",
|
| 362 |
+
"use sunscreen and recheck it monthly for any change in size, shape or colour"),
|
| 363 |
+
"melanoma_ambiguous": ("a mole-type lesion that cannot be told apart from melanoma by photo or text", 2,
|
| 364 |
+
"a pigmented spot where an ordinary mole and an early melanoma can look alike",
|
| 365 |
+
"have it examined in person to be safe"),
|
| 366 |
+
"melanoma": ("a pigmented lesion with features that can go with melanoma", 2,
|
| 367 |
+
"a mole or spot that is changing, irregular, multi-coloured or growing",
|
| 368 |
+
"only an in-person exam (and biopsy if needed) can tell"),
|
| 369 |
+
"bcc": ("a possible basal cell carcinoma (a common skin cancer)", 2,
|
| 370 |
+
"a pearly or shiny bump or a sore that bleeds, crusts and doesn't heal",
|
| 371 |
+
"it is usually slow-growing and very treatable when found early"),
|
| 372 |
+
"ak": ("actinic keratosis (a sun-damage patch that can become precancerous)", 2,
|
| 373 |
+
"a rough, scaly patch on sun-exposed skin",
|
| 374 |
+
"it is best treated early, so get it examined"),
|
| 375 |
+
"bullous": ("a blistering (bullous) skin disease", 2,
|
| 376 |
+
"large or widespread blisters, which can be an autoimmune condition",
|
| 377 |
+
"blistering conditions need prompt in-person assessment"),
|
| 378 |
+
"cellulitis": ("cellulitis (a spreading skin infection)", 2,
|
| 379 |
+
"a red, hot, swollen, painful area that is spreading",
|
| 380 |
+
"a spreading infection needs prompt assessment and usually antibiotics"),
|
| 381 |
+
"lupus": ("a possible autoimmune skin condition (such as lupus)", 2,
|
| 382 |
+
"a rash on sun-exposed skin or the cheeks, often with joint pain or fatigue",
|
| 383 |
+
"this usually needs blood tests and specialist review"),
|
| 384 |
+
"systemic": ("a rash that may be part of a wider (systemic) illness", 2,
|
| 385 |
+
"a rash together with fever, joint pain, or feeling generally unwell",
|
| 386 |
+
"rash plus whole-body symptoms deserves prompt medical review"),
|
| 387 |
+
"vasculitis": ("possible vasculitis (inflamed small blood vessels)", 2,
|
| 388 |
+
"small purple, non-blanching spots that often start on the lower legs",
|
| 389 |
+
"needs prompt medical assessment and tests"),
|
| 390 |
+
"impetigo": ("impetigo (a bacterial skin infection)", 1,
|
| 391 |
+
"honey-coloured crusts and sores, most common on the face and in children",
|
| 392 |
+
"keep it clean and covered, don't share towels, wash hands often β it usually needs a prescription"),
|
| 393 |
+
"drug": ("a drug (medication) rash", 1,
|
| 394 |
+
"a widespread rash that began days after starting a new medicine",
|
| 395 |
+
"don't stop a prescribed medicine on your own, but contact your doctor or pharmacist promptly"),
|
| 396 |
+
"herpes": ("a herpes simplex (cold sore / genital herpes) outbreak", 1,
|
| 397 |
+
"clustered small blisters that crust, often tingling or burning first",
|
| 398 |
+
"avoid touching it, wash hands, and avoid close contact until healed; a doctor can confirm and treat"),
|
| 399 |
+
"shingles": ("shingles (herpes zoster)", 2,
|
| 400 |
+
"a painful, burning, one-sided band of blisters",
|
| 401 |
+
"shingles is best treated early and, near the eye, needs urgent care"),
|
| 402 |
+
"fungal": ("a fungal skin infection (such as ringworm / tinea / candida)", 1,
|
| 403 |
+
"an itchy, ring-shaped or red scaly patch, often in warm, moist areas",
|
| 404 |
+
"keep the area clean and dry; it often needs a proper antifungal from a pharmacist or doctor"),
|
| 405 |
+
"nailfungus": ("a fungal nail infection", 1,
|
| 406 |
+
"thickened, yellowish, brittle nails",
|
| 407 |
+
"keep nails short and dry; treatment usually needs a doctor or pharmacist"),
|
| 408 |
+
"scabies": ("scabies (a mite infestation)", 1,
|
| 409 |
+
"intense itching that's worse at night, with tiny burrows or bumps between fingers, wrists or waist",
|
| 410 |
+
"it spreads by close contact and needs a prescribed treatment; household contacts are usually treated too"),
|
| 411 |
+
"lyme": ("possible early Lyme disease", 1,
|
| 412 |
+
"an expanding red ring after a tick bite",
|
| 413 |
+
"this needs prompt testing/treatment, so see a doctor soon"),
|
| 414 |
+
"warts": ("warts or molluscum (viral skin growths)", 1,
|
| 415 |
+
"small rough or dome-shaped bumps caused by a virus",
|
| 416 |
+
"avoid picking or sharing towels; they often clear on their own but a doctor can treat persistent ones"),
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
# classifier label keyword -> condition key (first match wins)
|
| 420 |
+
_LABEL_MAP = [
|
| 421 |
+
("nevi", None), ("melanoma", "melanoma"), ("basal cell", "bcc"), ("actinic", "ak"),
|
| 422 |
+
("benign keratosis", "bkl"), ("seborrheic keratos", "bkl"), ("seborrheic derm", "seb_derm"),
|
| 423 |
+
("dermatofibroma", "dermatofibroma"), ("vascular", "vascular"),
|
| 424 |
+
("acne", "acne"), ("rosacea", "acne"), ("eczema", "eczema"), ("atopic", "eczema"),
|
| 425 |
+
("psoriasis", "psoriasis"), ("lichen", "psoriasis"), ("contact derm", "contact"),
|
| 426 |
+
("poison", "contact"), ("urticaria", "urticaria"), ("hives", "urticaria"),
|
| 427 |
+
("alopecia", "alopecia"), ("hair", "alopecia"), ("pigment", "pigment"),
|
| 428 |
+
("vitiligo", "pigment"), ("bullous", "bullous"), ("pemphig", "bullous"),
|
| 429 |
+
("cellulitis", "cellulitis"), ("lupus", "lupus"), ("connective", "lupus"),
|
| 430 |
+
("systemic", "systemic"), ("vasculitis", "vasculitis"), ("impetigo", "impetigo"),
|
| 431 |
+
("bacterial", "impetigo"), ("drug", "drug"), ("exanthem", "drug"),
|
| 432 |
+
("shingles", "shingles"), ("zoster", "shingles"), ("herpes", "herpes"),
|
| 433 |
+
("std", "herpes"), ("nail", "nailfungus"), ("fungal", "fungal"), ("tinea", "fungal"),
|
| 434 |
+
("ringworm", "fungal"), ("candid", "fungal"), ("scabies", "scabies"),
|
| 435 |
+
("infestation", "scabies"), ("lyme", "lyme"), ("wart", "warts"),
|
| 436 |
+
("molluscum", "warts"), ("viral", "warts"), ("tumor", "bkl"), ("mole", None),
|
| 437 |
+
]
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def label_to_key(label):
|
| 441 |
+
l = label.lower().replace("[lesion-model]", "").strip()
|
| 442 |
+
if ("nevi" in l or "mole" in l) and "melanoma" in l:
|
| 443 |
+
return "melanoma_ambiguous"
|
| 444 |
+
if l in ("nv", "melanocytic nevi") or "melanocytic nevi" in l or l.startswith("nevi"):
|
| 445 |
+
return "nevus"
|
| 446 |
+
for kw, key in _LABEL_MAP:
|
| 447 |
+
if kw in l:
|
| 448 |
+
return key or "nevus"
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
# ---------------------------------------------------------------------------
|
| 453 |
+
# Negation-aware phrase matching
|
| 454 |
+
# ---------------------------------------------------------------------------
|
| 455 |
+
_NEGATION = re.compile(
|
| 456 |
+
r"\b(no|not|never|without|don'?t|doesn'?t|didn'?t|isn'?t|aren'?t|hasn'?t|haven'?t|nothing|neither|nor|none)\b"
|
| 457 |
+
r"[^.;!?\n]{0,25}$",
|
| 458 |
+
re.I,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _find(pattern, text):
|
| 463 |
+
"""True if `pattern` occurs in `text` and is not directly negated."""
|
| 464 |
+
for m in re.finditer(pattern, text, re.I):
|
| 465 |
+
before = text[max(0, m.start() - 30): m.start()]
|
| 466 |
+
# only look inside the same clause
|
| 467 |
+
before = re.split(r"[.;!?\n]|\bbut\b|\bhowever\b", before)[-1]
|
| 468 |
+
if not _NEGATION.search(before + " "):
|
| 469 |
+
return True
|
| 470 |
+
return False
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
# (feature name, regex)
|
| 474 |
+
FEATURES = {
|
| 475 |
+
"itch": r"\bitch(?:y|ing|es)?\b|\bpruritus\b",
|
| 476 |
+
"burn": r"\bburning\b|\bstinging\b|\bstings?\b",
|
| 477 |
+
"pain": r"\bpain(?:ful)?\b|\btender(?:ness)?\b|\bsore\b|\bhurts?\b|\baches?\b",
|
| 478 |
+
"severe_pain": r"\b(severe|intense|excruciating|unbearable|terrible)\b[^.]{0,15}\bpain\b|\bpain\b[^.]{0,15}\b(severe|unbearable|excruciating)\b",
|
| 479 |
+
"dry": r"\bdry(?:ness)?\b|\bflak(?:y|ing)\b|\bpeeling\b|\bcracked\b",
|
| 480 |
+
"scale": r"\bscal(?:y|es|ing)\b|\bsilvery\b|\bplaques?\b|\bthick patch",
|
| 481 |
+
"red": r"\bred(?:ness)?\b|\binflamed\b|\bpink\b",
|
| 482 |
+
"swollen": r"\bswoll?en\b|\bswelling\b|\bpuffy\b",
|
| 483 |
+
"warm": r"\bwarm\b|\bhot to (?:the )?touch\b|\bfeels hot\b",
|
| 484 |
+
"blister": r"\bblisters?\b|\bblistering\b|\bvesicles?\b|\bfluid[- ]filled\b",
|
| 485 |
+
"crust": r"\bcrust(?:y|ed|ing)?\b|\bscab(?:s|bing)?\b|\bhoney[- ]colou?red\b",
|
| 486 |
+
"ooze": r"\booz(?:e|es|ing)\b|\bweeping\b|\bdischarge\b|\bpus\b|\bpurulent\b",
|
| 487 |
+
"bleed": r"\bbleed(?:s|ing)?\b|\bbled\b",
|
| 488 |
+
"nonheal": r"\b(won'?t|doesn'?t|not|never|isn'?t|hasn'?t)\b[^.]{0,12}\bheal(?:ing|ed)?\b|\bnon[- ]?healing\b|\bslow to heal\b",
|
| 489 |
+
"growing": r"\bgrow(?:ing|n|s)\b|\bgot bigger\b|\bgetting bigger\b|\benlarg(?:ed|ing)\b|\bincreas(?:ed|ing) in size\b",
|
| 490 |
+
"rapid": r"\b(rapid(?:ly)?|quick(?:ly)?|fast|sudden(?:ly)?|overnight|within (?:days|a week|weeks))\b[^.]{0,25}\b(grow|grew|growing|bigger|spread|spreading|chang|appear)\w*|\bgrew (?:very )?(?:fast|quickly)\b",
|
| 491 |
+
"changing": r"\bchang(?:ed|ing|es)\b|\bevolv(?:ed|ing)\b|\bdarker\b|\bdarkened\b|\bnew colou?r",
|
| 492 |
+
"irregular": r"\birregular\b|\buneven\b|\basymmetr\w+|\bjagged\b|\bragged\b|\bnotched\b|\bblurred border\b|\bmultiple colou?rs\b|\bmulti[- ]?colou?red\b|\bblack and brown\b|\bseveral colou?rs\b",
|
| 493 |
+
"dark_spot": r"\bmole\b|\bnevus\b|\bdark spot\b|\bbrown spot\b|\bblack spot\b|\bpigmented\b|\bfreckle\b",
|
| 494 |
+
"pearly": r"\bpearly\b|\bshiny\b|\bwaxy\b|\btranslucent\b|\brolled edge\b|\bvisible (?:tiny )?(?:blood )?vessels\b",
|
| 495 |
+
"stuck_on": r"\bstuck[- ]on\b|\bwaxy\b|\bwarty\b|\bgreasy\b",
|
| 496 |
+
"ring": r"\bring[- ]?(?:shaped|like)?\b|\bcircular\b|\bcentral clearing\b|\bclear(?:s|ing)? in the (?:middle|centre|center)\b",
|
| 497 |
+
"spread": r"\bspread(?:ing|s)?\b|\bmore (?:spots|patches|areas)\b|\bmultiple (?:spots|patches|areas)\b|\beverywhere\b|\bwidespread\b",
|
| 498 |
+
"night_itch": r"\b(night|bed|bedtime|sleep)\b[^.]{0,25}\bitch|\bitch\w*[^.]{0,25}\b(night|bed|bedtime)\b",
|
| 499 |
+
"contacts_itch": r"\b(family|household|partner|sibling|roommate|kids?|child(?:ren)?|boyfriend|girlfriend|husband|wife|everyone)\b[^.]{0,40}\b(itch|rash|same)\b|\bothers? (?:at home|in (?:my|the) house)\b",
|
| 500 |
+
"between_fingers": r"\bbetween (?:my |the )?(?:fingers|toes)\b|\bwrists?\b|\bwaistline\b|\bburrows?\b",
|
| 501 |
+
"fever": r"\bfever\b|\bfeverish\b|\bchills\b|\bhigh temperature\b|\btemperature of 3[89]\b|\b10[0-4]\s?Β°?\s?f\b",
|
| 502 |
+
"unwell": r"\bunwell\b|\bfatigue\b|\bexhausted\b|\bmalaise\b|\bweak\b|\bachy\b|\bflu[- ]like\b|\bjoint (?:pain|aches?)\b|\bmouth ulcers?\b",
|
| 503 |
+
"joint": r"\bjoint (?:pain|ache|swelling|stiffness)\b|\barthritis\b",
|
| 504 |
+
"sun_rash": r"\b(sun|sunlight|sun[- ]exposed)\b[^.]{0,25}\b(worse|rash|flare|trigger)\b|\bbutterfly\b|\bcheeks?\b[^.]{0,20}\brash\b",
|
| 505 |
+
"purple_spots": r"\bpurp(?:le|lish)\b[^.]{0,20}\b(spots?|dots?|patch(?:es)?|rash|bruis\w*)\b|\bnon[- ]?blanching\b|\bpetechia\w*\b|\bpurpura\b",
|
| 506 |
+
"lower_legs": r"\b(lower )?(legs?|shins?|ankles?|calves)\b",
|
| 507 |
+
"new_med": r"\b(started|began|new|prescribed|took|taking|course of)\b[^.]{0,25}\b(medicine|medication|antibiotic|tablet|pill|drug|painkiller|ibuprofen|paracetamol|acetaminophen|penicillin|sulfa)\b",
|
| 508 |
+
"tick": r"\btick\b|\bbull'?s[- ]?eye\b|\bhiking\b|\bcamping\b|\bwoods\b",
|
| 509 |
+
"one_side_band": r"\b(one side|one[- ]sided|band|strip|stripe|belt|along a nerve)\b",
|
| 510 |
+
"tingle_first": r"\b(tingl\w+|burning|numb\w*)\b[^.]{0,30}\bbefore\b|\bbefore\b[^.]{0,30}\b(blisters?|rash)\b",
|
| 511 |
+
"lip_mouth": r"\bcold sores?\b|\bfever blisters?\b|\b(lip|lips|mouth|genital|genitals|private area)\b",
|
| 512 |
+
"hives": r"\bhives\b|\bwelts?\b|\burticaria\b|\bwheals?\b|\bcome and go\b|\bcomes? and goes?\b|\bgo(?:es)? away within\b",
|
| 513 |
+
"swelling_face": r"\b(lips?|tongue|face|throat|eyelids?)\b[^.]{0,20}\bswoll?en\b|\bswelling of (?:the )?(?:lips?|tongue|face|throat)\b",
|
| 514 |
+
"pimple": r"\bpimples?\b|\bzits?\b|\bblackheads?\b|\bwhiteheads?\b|\bacne\b|\bbreakouts?\b|\bcysts?\b|\bpustules?\b",
|
| 515 |
+
"oily": r"\boily\b|\bgreasy skin\b|\bmakeup\b|\bperiod\b|\bhormon\w+",
|
| 516 |
+
"scalp": r"\bscalp\b|\beyebrows?\b|\bdandruff\b|\bbehind (?:the |my )?ears?\b",
|
| 517 |
+
"hair_loss": r"\bhair (?:loss|fall(?:ing)?|thinning)\b|\bbald\b|\bbald patch\b|\bhair (?:is )?(?:coming|falling) out\b|\bthinning\b",
|
| 518 |
+
"pale_patch": r"\b(white|pale|light(?:er)?|depigmented)\b[^.]{0,15}\b(patch(?:es)?|spots?|areas?)\b|\bvitiligo\b|\bmelasma\b|\bdarker patches\b",
|
| 519 |
+
"red_vessel": r"\b(cherry|red)\b[^.]{0,10}\b(dots?|spots?|bumps?|angioma)\b|\bangioma\b|\bblood vessel\b",
|
| 520 |
+
"nodule": r"\b(firm|hard)\b[^.]{0,10}\b(bump|nodule|lump)\b|\bdimple(?:s|d)?\b|\bpinch(?:ed)?\b[^.]{0,10}\bdimple\b",
|
| 521 |
+
"thick_nail": r"\b(thick(?:ened)?|yellow(?:ish)?|brittle|crumbl\w+)\b[^.]{0,15}\b(nails?|toenails?|fingernails?)\b|\bnail (?:fungus|infection)\b",
|
| 522 |
+
"moist_area": r"\b(groin|armpits?|between (?:my )?toes|athlete'?s foot|under (?:the |my )?breasts?|skin folds?|jock itch|sweaty)\b",
|
| 523 |
+
"wart_like": r"\bwarts?\b|\brough bumps?\b|\bcauliflower\b|\bdome[- ]shaped\b|\bumbilicated\b|\bmolluscum\b|\bplantar\b",
|
| 524 |
+
"sun_damage": r"\b(sun[- ]?damage[d]?|years in the sun|outdoor(?:s)? (?:work|job)|sunburns?|tanning|fair skin|sun[- ]exposed)\b",
|
| 525 |
+
"rough_patch": r"\brough (?:patch|spot|area)\b|\bsandpaper\b|\bscaly (?:patch|spot)\b",
|
| 526 |
+
"after_exposure": r"\b(after|since)\b[^.]{0,25}\b(touch\w*|using|new (?:soap|lotion|cream|detergent|perfume|jewell?ery|product|shampoo)|plant|poison ivy|nickel|gloves|latex|cosmetic|hair dye|detergent)\b|\bnew (?:soap|lotion|cream|detergent|perfume|jewell?ery|shampoo)\b",
|
| 527 |
+
"child": r"\b(my (?:son|daughter|child|baby|toddler|kid)|school)\b",
|
| 528 |
+
"face": r"\b(face|cheeks?|nose|forehead|chin)\b",
|
| 529 |
+
"skin_infection_fresh": r"\b(cut|scrape|insect bite|bite|wound|scratch)\b[^.]{0,25}\b(then|and now|became|got|turned)\b",
|
| 530 |
+
"stress_flare": r"\bflare[sd]?\b|\bcomes? and goes?\b|\bon and off\b|\brecurr\w+\b|\bsince (?:childhood|i was (?:a )?(?:kid|child))\b",
|
| 531 |
+
"folds": r"\b(elbow|elbows|knee|knees|behind (?:the |my )?knees|inner elbows?|crook)\b",
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
# condition -> {feature: weight}
|
| 535 |
+
RULES = {
|
| 536 |
+
"acne": {"pimple": 4, "oily": 1, "face": 1, "pain": 0.5},
|
| 537 |
+
"eczema": {"itch": 2, "dry": 2, "stress_flare": 1.5, "folds": 1.5, "red": 0.5, "child": 0.5},
|
| 538 |
+
"psoriasis": {"scale": 3, "folds": 1.5, "dry": 0.5, "stress_flare": 0.5, "scalp": 0.5},
|
| 539 |
+
"contact": {"after_exposure": 3.5, "itch": 1, "red": 0.5, "blister": 0.5, "burn": 0.5},
|
| 540 |
+
"urticaria": {"hives": 4, "itch": 1, "swelling_face": 0.5},
|
| 541 |
+
"seb_derm": {"scalp": 2, "dry": 1, "red": 0.5, "itch": 0.5, "face": 0.5},
|
| 542 |
+
"alopecia": {"hair_loss": 5},
|
| 543 |
+
"pigment": {"pale_patch": 5},
|
| 544 |
+
"vascular": {"red_vessel": 5},
|
| 545 |
+
"bkl": {"stuck_on": 3, "dark_spot": 1},
|
| 546 |
+
"dermatofibroma": {"nodule": 4},
|
| 547 |
+
"nevus": {"dark_spot": 2},
|
| 548 |
+
"melanoma": {"dark_spot": 1.5, "changing": 2.5, "irregular": 3, "growing": 1.5, "rapid": 2.5, "bleed": 2, "nonheal": 1},
|
| 549 |
+
"bcc": {"pearly": 3, "bleed": 2, "nonheal": 3, "crust": 1, "sun_damage": 1, "red_vessel": 0.5},
|
| 550 |
+
"ak": {"rough_patch": 3, "sun_damage": 2, "scale": 1},
|
| 551 |
+
"bullous": {"blister": 3, "spread": 1, "pain": 0.5, "unwell": 0.5},
|
| 552 |
+
"cellulitis": {"red": 1.5, "warm": 3, "swollen": 2, "pain": 1.5, "spread": 1.5, "fever": 2, "skin_infection_fresh": 1.5},
|
| 553 |
+
"lupus": {"sun_rash": 3.5, "joint": 2, "unwell": 1.5, "face": 0.5},
|
| 554 |
+
"systemic": {"fever": 2, "unwell": 2, "joint": 1, "spread": 1.5},
|
| 555 |
+
"vasculitis": {"purple_spots": 4.5, "lower_legs": 1, "pain": 0.5},
|
| 556 |
+
"impetigo": {"crust": 3, "ooze": 1.5, "child": 1.5, "face": 1, "skin_infection_fresh": 1},
|
| 557 |
+
"drug": {"new_med": 3.5, "spread": 1.5, "itch": 0.5, "red": 0.5},
|
| 558 |
+
"herpes": {"lip_mouth": 2, "blister": 2.5, "tingle_first": 2, "burn": 1},
|
| 559 |
+
"shingles": {"one_side_band": 3, "blister": 2, "pain": 2, "burn": 1.5, "tingle_first": 1},
|
| 560 |
+
"fungal": {"ring": 3.5, "moist_area": 2.5, "itch": 1.5, "scale": 1, "red": 0.5},
|
| 561 |
+
"nailfungus": {"thick_nail": 5},
|
| 562 |
+
"scabies": {"night_itch": 4, "between_fingers": 3, "contacts_itch": 3, "itch": 1},
|
| 563 |
+
"lyme": {"tick": 3, "ring": 3, "spread": 0.5, "fever": 0.5},
|
| 564 |
+
"warts": {"wart_like": 5},
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
# Needs at least this much combined score to be named from text alone.
|
| 568 |
+
_TEXT_MIN_SCORE = 3.0
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def detect_features(text):
|
| 572 |
+
t = (text or "").lower()
|
| 573 |
+
return {name: _find(pat, t) for name, pat in FEATURES.items()}
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
# Emergencies: advise urgent in-person care immediately, any turn.
|
| 577 |
+
EMERGENCY_PATTERNS = [
|
| 578 |
+
(r"\b(can'?t|cannot|trouble|difficulty|hard to)\s+breath\w*|\bshort(?:ness)? of breath\b|\bwheez\w+", "trouble breathing"),
|
| 579 |
+
(r"\bswelling (?:of|in) (?:my |the )?(?:throat|tongue|lips|face)\b|\b(throat|tongue|lips?)\b[^.]{0,20}\b(swelling|swollen|swell\w*)\b|\b(swelling|swollen)\b[^.]{0,15}\b(throat|tongue)\b", "swelling of the throat, tongue or lips"),
|
| 580 |
+
(r"\bfever\b[^.]{0,60}\b(spreading|red streaks?|purple|rapid)\b|\bred streaks?\b", "fever or red streaks with a skin problem"),
|
| 581 |
+
(r"\b(peeling|sloughing|shedding)\b[^.]{0,25}\b(skin|sheets)\b[^.]{0,40}\b(mouth|eyes?|fever)\b|\bsores? (?:in|on) (?:my )?(?:mouth|eyes?)\b[^.]{0,30}\brash\b", "widespread skin peeling with mouth/eye involvement"),
|
| 582 |
+
(r"\b(rapidly|quickly|fast)\b[^.]{0,20}\bspreading\b[^.]{0,30}\b(red|redness|rash|infection)\b|\bspreading (?:redness|infection)\b", "rapidly spreading redness"),
|
| 583 |
+
(r"\bblister\w*\b[^.]{0,30}\b(eye|eyes|eyelid)\b|\bshingles\b[^.]{0,30}\b(eye|forehead|nose)\b", "blisters near the eye"),
|
| 584 |
+
(r"\buncontrolled bleeding\b|\bwon'?t stop bleeding\b|\bbleeding (?:a lot|heavily|badly)\b", "bleeding that won't stop"),
|
| 585 |
+
(r"\b(?:feel(?:ing)?|am|is|got|getting|became|suddenly)\s+(?:very\s+)?confused\b|\bfaint(?:ing|ed)\b|\bfeel(?:ing)? faint\b|\bpassed out\b|\bblack(?:ed)? out\b|\bseizures?\b", "confusion or fainting"),
|
| 586 |
+
]
|
| 587 |
+
|
| 588 |
+
# Red flags that push severity to High on their own.
|
| 589 |
+
FLAG_RULES = [
|
| 590 |
+
("rapid", "it has been growing or changing quickly"),
|
| 591 |
+
("irregular", "an irregular shape, border or several colours"),
|
| 592 |
+
("bleed", "it bleeds"),
|
| 593 |
+
("nonheal", "it doesn't heal"),
|
| 594 |
+
]
|
| 595 |
+
FLAG_COMBOS = [
|
| 596 |
+
(("dark_spot", "changing"), "a mole/spot that is changing"),
|
| 597 |
+
(("dark_spot", "growing"), "a mole/spot that is getting bigger"),
|
| 598 |
+
(("fever", "red"), "fever together with skin redness"),
|
| 599 |
+
(("fever", "spread"), "fever together with a spreading rash"),
|
| 600 |
+
(("warm", "swollen", "spread"), "warm, swollen, spreading skin"),
|
| 601 |
+
(("unwell", "blister"), "blisters with feeling unwell"),
|
| 602 |
+
(("severe_pain",), "severe pain"),
|
| 603 |
+
]
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def detect_emergency(text):
|
| 607 |
+
t = (text or "").lower()
|
| 608 |
+
hits = []
|
| 609 |
+
for pat, label in EMERGENCY_PATTERNS:
|
| 610 |
+
if _find(pat, t):
|
| 611 |
+
hits.append(label)
|
| 612 |
+
return hits
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def detect_flags(text, feats=None):
|
| 616 |
+
feats = feats or detect_features(text)
|
| 617 |
+
out = []
|
| 618 |
+
for f, label in FLAG_RULES:
|
| 619 |
+
if feats.get(f):
|
| 620 |
+
out.append(label)
|
| 621 |
+
for combo, label in FLAG_COMBOS:
|
| 622 |
+
if all(feats.get(c) for c in combo):
|
| 623 |
+
out.append(label)
|
| 624 |
+
# "bleeds" alone on e.g. a picked pimple is weak; keep but dedupe
|
| 625 |
+
return list(dict.fromkeys(out))
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def text_candidates(user_text):
|
| 629 |
+
"""Return [(key, score)] sorted best-first, from symptom wording alone."""
|
| 630 |
+
feats = detect_features(user_text)
|
| 631 |
+
scored = []
|
| 632 |
+
for key, weights in RULES.items():
|
| 633 |
+
s = sum(w for f, w in weights.items() if feats.get(f))
|
| 634 |
+
if s > 0:
|
| 635 |
+
scored.append((key, s))
|
| 636 |
+
scored.sort(key=lambda kv: -kv[1])
|
| 637 |
+
return [(k, s) for k, s in scored if s >= _TEXT_MIN_SCORE], feats
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def image_candidates(preds):
|
| 641 |
+
"""Map classifier output to [(key, prob)], best first. Second-opinion lesion model weighted in."""
|
| 642 |
+
agg = {}
|
| 643 |
+
for p in (preds or [])[:5]:
|
| 644 |
+
key = label_to_key(p["label"])
|
| 645 |
+
if key:
|
| 646 |
+
w = p["score"] * (1.1 if p["label"].startswith("[lesion-model]") else 1.0)
|
| 647 |
+
agg[key] = agg.get(key, 0.0) + w
|
| 648 |
+
return sorted(agg.items(), key=lambda kv: -kv[1])
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def long_duration(text):
|
| 652 |
+
t = (text or "").lower()
|
| 653 |
+
return bool(re.search(r"\b(\d+|several|few|many)\s*(weeks?|months?|years?)\b|\bfor (?:months|years|a long time)\b|\bsince (?:last|childhood)\b", t)) and not re.search(
|
| 654 |
+
r"\b(1|2|one|two|a couple of|couple)\s*days?\b", t
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def run_offline_assessment(user_text, preds=None):
|
| 659 |
+
"""Core engine: returns dict(rank, text). `user_text` = everything the user said."""
|
| 660 |
+
t_cands, feats = text_candidates(user_text)
|
| 661 |
+
i_cands = image_candidates(preds)
|
| 662 |
+
emergencies = detect_emergency(user_text)
|
| 663 |
+
flags = detect_flags(user_text, feats)
|
| 664 |
+
|
| 665 |
+
# blend: text score normalised to ~0-1, image prob 0-1; image counts a bit more
|
| 666 |
+
combined = {}
|
| 667 |
+
if t_cands:
|
| 668 |
+
top_t = t_cands[0][1]
|
| 669 |
+
for k, s in t_cands[:5]:
|
| 670 |
+
combined[k] = combined.get(k, 0) + 0.9 * (s / (top_t + 2.0))
|
| 671 |
+
for k, pr in i_cands[:3]:
|
| 672 |
+
combined[k] = combined.get(k, 0) + 1.2 * pr
|
| 673 |
+
ranked = sorted(combined.items(), key=lambda kv: -kv[1])
|
| 674 |
+
|
| 675 |
+
# --- severity ---------------------------------------------------------
|
| 676 |
+
rank = 0
|
| 677 |
+
reasons = []
|
| 678 |
+
if ranked:
|
| 679 |
+
top_key = ranked[0][0]
|
| 680 |
+
rank = CONDITION_KB[top_key][1]
|
| 681 |
+
# if either of the two leading candidates is High, don't under-call it
|
| 682 |
+
for k, sc in ranked[:2]:
|
| 683 |
+
if CONDITION_KB[k][1] == 2 and sc >= 0.35:
|
| 684 |
+
rank = 2
|
| 685 |
+
top_key = top_key if CONDITION_KB[top_key][1] == 2 else k if sc >= ranked[0][1] * 0.6 else top_key
|
| 686 |
+
if i_cands and CONDITION_KB[i_cands[0][0]][1] == 2 and i_cands[0][1] >= 0.2:
|
| 687 |
+
rank = 2
|
| 688 |
+
if flags:
|
| 689 |
+
rank = 2
|
| 690 |
+
reasons += flags
|
| 691 |
+
if emergencies:
|
| 692 |
+
rank = 2
|
| 693 |
+
|
| 694 |
+
# --- wording ----------------------------------------------------------
|
| 695 |
+
parts = []
|
| 696 |
+
if emergencies:
|
| 697 |
+
parts.append(
|
| 698 |
+
"β οΈ **What you describe β " + _natural_join(emergencies) + " β can be urgent.** "
|
| 699 |
+
"Please seek in-person or emergency care promptly rather than waiting on this chat."
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
if not ranked:
|
| 703 |
+
if rank == 2:
|
| 704 |
+
parts.append(
|
| 705 |
+
"I can't match this to a specific condition from what's been described, but the warning signs "
|
| 706 |
+
"above are enough for me to say it should be looked at in person."
|
| 707 |
+
)
|
| 708 |
+
else:
|
| 709 |
+
parts.append(
|
| 710 |
+
"From what's been described I can't match this to a specific condition with any confidence. "
|
| 711 |
+
"A photo would help (use the π button), or tell me more about how it looks and feels."
|
| 712 |
+
)
|
| 713 |
+
text = _assemble(parts, rank, reasons, None, None, emergencies)
|
| 714 |
+
return {"rank": rank, "text": text, "key": None}
|
| 715 |
+
|
| 716 |
+
top_key = ranked[0][0]
|
| 717 |
+
# pick the displayed top: prefer the highest-ranked among the leading two when severity is High
|
| 718 |
+
if rank == 2 and CONDITION_KB[top_key][1] < 2:
|
| 719 |
+
for k, _ in ranked[:3]:
|
| 720 |
+
if CONDITION_KB[k][1] == 2:
|
| 721 |
+
top_key = k
|
| 722 |
+
break
|
| 723 |
+
name, krank, desc, care = CONDITION_KB[top_key]
|
| 724 |
+
|
| 725 |
+
why = []
|
| 726 |
+
if i_cands and any(k == top_key for k, _ in i_cands[:2]):
|
| 727 |
+
why.append("the image classifier's result points that way")
|
| 728 |
+
matched = [f for f, w in RULES.get(top_key, {}).items() if feats.get(f)]
|
| 729 |
+
if matched:
|
| 730 |
+
why.append("your description (" + _natural_join([_FEATURE_WORDS.get(m, m.replace("_", " ")) for m in matched[:4]]) + ") fits")
|
| 731 |
+
why_txt = (" β " + " and ".join(why)) if why else ""
|
| 732 |
+
parts.append(f"**Most consistent with: {name}**{why_txt}. This is {desc}.")
|
| 733 |
+
|
| 734 |
+
others = [CONDITION_KB[k][0] for k, sc in ranked[1:3] if k != top_key and sc >= 0.5 * ranked[0][1]]
|
| 735 |
+
if others:
|
| 736 |
+
parts.append("Also possible: " + _natural_join(others) + ".")
|
| 737 |
+
|
| 738 |
+
if top_key == "melanoma_ambiguous":
|
| 739 |
+
parts.append("The classifier's category groups ordinary moles together with melanoma, so I can't separate them β and when that's the case I treat it as High rather than assuming it's benign.")
|
| 740 |
+
|
| 741 |
+
text = _assemble(parts, rank, reasons, top_key, krank, emergencies, care)
|
| 742 |
+
return {"rank": rank, "text": text, "key": top_key}
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
_FEATURE_WORDS = {
|
| 746 |
+
"itch": "itching", "burn": "burning", "pain": "pain/tenderness", "dry": "dryness", "scale": "scaling",
|
| 747 |
+
"red": "redness", "swollen": "swelling", "warm": "warmth", "blister": "blisters", "crust": "crusting",
|
| 748 |
+
"ooze": "oozing", "bleed": "bleeding", "nonheal": "not healing", "growing": "growth", "changing": "change over time",
|
| 749 |
+
"irregular": "irregular features", "dark_spot": "a dark spot/mole", "pearly": "a pearly/shiny look",
|
| 750 |
+
"ring": "a ring shape", "spread": "spreading", "night_itch": "night-time itching", "fever": "fever",
|
| 751 |
+
"hives": "come-and-go welts", "pimple": "pimples", "hair_loss": "hair loss", "stuck_on": "a stuck-on look",
|
| 752 |
+
"after_exposure": "a new product or plant exposure", "tick": "a tick/outdoor link", "wart_like": "wart-like bumps",
|
| 753 |
+
"new_med": "a new medicine", "purple_spots": "purple spots", "moist_area": "a warm, moist location",
|
| 754 |
+
"rough_patch": "a rough patch", "sun_damage": "sun exposure", "scalp": "scalp involvement",
|
| 755 |
+
"contacts_itch": "others at home being affected", "between_fingers": "finger/wrist involvement",
|
| 756 |
+
"sun_rash": "sun-triggered rash", "joint": "joint symptoms", "unwell": "feeling unwell",
|
| 757 |
+
"one_side_band": "a one-sided band", "tingle_first": "tingling before the rash", "lip_mouth": "lip/mouth/genital area",
|
| 758 |
+
"stress_flare": "flare-ups that come and go", "folds": "skin folds/elbows/knees", "nodule": "a firm nodule",
|
| 759 |
+
"thick_nail": "thickened nails", "pale_patch": "pale or dark patches", "red_vessel": "a red vessel-type spot",
|
| 760 |
+
}
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _natural_join(items):
|
| 764 |
+
items = [i for i in items if i]
|
| 765 |
+
if len(items) <= 1:
|
| 766 |
+
return "".join(items)
|
| 767 |
+
return ", ".join(items[:-1]) + " and " + items[-1]
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _assemble(parts, rank, reasons, key, krank, emergencies, care=None):
|
| 771 |
+
out = list(parts)
|
| 772 |
+
nxt = ("Treat this as urgent: get in-person or emergency care now rather than waiting on this chat."
|
| 773 |
+
if emergencies else RANK_NEXT[rank])
|
| 774 |
+
sev = f"{RANK_EMOJI[rank]} **Severity: {RANK_NAME[rank]}** β {nxt}"
|
| 775 |
+
if reasons and rank == 2:
|
| 776 |
+
sev += " Red flags noticed: " + _natural_join(reasons) + "."
|
| 777 |
+
out.append(sev)
|
| 778 |
+
if care and rank == 0:
|
| 779 |
+
out.append(f"**General care:** {care}.")
|
| 780 |
+
elif care and rank == 1 and not emergencies:
|
| 781 |
+
out.append(f"**In the meantime:** {care}.")
|
| 782 |
+
elif care and rank == 2 and not emergencies:
|
| 783 |
+
out.append(f"**Worth knowing:** {care[0].upper() + care[1:]}.")
|
| 784 |
+
out.append(
|
| 785 |
+
"This is a preliminary read, not a diagnosis β only an in-person exam (and sometimes tests) can confirm it."
|
| 786 |
+
)
|
| 787 |
+
return "\n\n".join(out)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def offline_assessment(user_text, preds=None, followup_hint=True):
|
| 791 |
+
"""One-shot assessment (used by the Quick Image Check tab when all models fail)."""
|
| 792 |
+
res = run_offline_assessment(user_text or "", preds)
|
| 793 |
+
text = res["text"]
|
| 794 |
+
if followup_hint and not user_text:
|
| 795 |
+
text += "\n\n_Tip: describe how long it's been there, whether it itches/hurts/bleeds and whether it has changed β in the Chat Assistant tab β to sharpen this._"
|
| 796 |
+
return text
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
# ---------------------------------------------------------------------------
|
| 800 |
+
# Offline multi-round chat
|
| 801 |
+
# ---------------------------------------------------------------------------
|
| 802 |
+
OFFLINE_TAG = "Offline assistant mode"
|
| 803 |
+
|
| 804 |
+
# (topic, regex that says it's already covered, question)
|
| 805 |
+
TOPIC_QUESTIONS = [
|
| 806 |
+
("where", r"\b(face|cheeks?|nose|forehead|chin|scalp|neck|arms?|hands?|fingers?|legs?|feet|foot|toes?|back|chest|stomach|belly|groin|armpits?|buttocks?|lips?|mouth|ears?|eyelids?|nails?|shoulders?|elbows?|knees?|thighs?|trunk|torso|body)\b",
|
| 807 |
+
"Where on your body is it, and is it in one spot or several places?"),
|
| 808 |
+
("when", r"\b(\d+|one|two|three|four|five|few|couple|several)\s*(days?|weeks?|months?|years?)\b|\b(yesterday|last (?:week|month|year)|since|always|recently|just (?:started|appeared)|started|began|for (?:a|the) (?:while|long))\b",
|
| 809 |
+
"How long have you had it, and did it start suddenly or gradually?"),
|
| 810 |
+
("look", r"\b(red|pink|brown|black|white|yellow|purple|scaly|flaky|bump|raised|flat|round|ring|blister|crust|patch|spot|rash|lump|plaque|dry|smooth|rough|shiny|waxy|swollen|pimple)\w*\b",
|
| 811 |
+
"What does it look like β colour, raised or flat, smooth or scaly, any blisters or crusts?"),
|
| 812 |
+
("feel", r"\bitch\w*|\bpain\w*|\bburn\w*|\bsting\w*|\btender\w*|\bbleed\w*|\bnumb\w*|\bsore\b|\bhurts?\b|\bno (?:itch|pain|symptoms)\b|\bdoesn'?t (?:itch|hurt)\b",
|
| 813 |
+
"Does it itch, burn, hurt or bleed β or is it completely symptom-free?"),
|
| 814 |
+
("change", r"\bchang\w+|\bgrow\w*|\bgrew\b|\bspread\w*|\bbigger\b|\bsame size\b|\bstable\b|\bunchanged\b|\bworse\b|\bbetter\b|\bimprov\w+|\bfading\b|\bstayed\b",
|
| 815 |
+
"Has it changed since you first noticed it β bigger, spreading, darker, better or worse?"),
|
| 816 |
+
("trigger", r"\bnew (?:soap|lotion|cream|detergent|medicine|medication|product)\b|\bplant\b|\bbite\w*\b|\btravel\w*\b|\bsun\w*\b|\ballerg\w+|\bstress\w*\b|\bcontact\b|\bexposed\b|\bnothing new\b|\bno (?:new|triggers?)\b|\bhiking\b|\bpets?\b|\bgym\b",
|
| 817 |
+
"Anything new around when it began β a product, medicine, plant, insect bite, travel or sun exposure?"),
|
| 818 |
+
("history", r"\btried\b|\btreat\w+\b|\bcream\b|\bointment\b|\bmedic\w+\b|\bprevious\w*\b|\bbefore\b|\bhappened before\b|\bfamily history\b|\bhistory of\b|\bfirst time\b|\bnever had\b|\bnothing (?:helps|worked)\b|\bdiabet\w+|\basthma\b|\ballerg\w+",
|
| 819 |
+
"Have you had anything like this before, tried any treatment (and did it help), or have any relevant history such as allergies, asthma, diabetes or skin cancer in the family?"),
|
| 820 |
+
("general", r"\bfever\b|\bunwell\b|\bfatigue\b|\btired\b|\bchills\b|\bjoint\b|\bfeel(?:ing)? (?:fine|well|ok|okay)\b|\bno fever\b|\bswollen glands?\b",
|
| 821 |
+
"Any fever, tiredness, joint pain, or generally feeling unwell alongside it?"),
|
| 822 |
+
]
|
| 823 |
+
|
| 824 |
+
_ASSESS_REQUEST = re.compile(
|
| 825 |
+
r"\b(what (?:is|could) (?:it|this)|what do you think|your (?:assessment|diagnosis|opinion|verdict)|give me (?:a|an|your) (?:assessment|diagnosis|answer|result)|just tell me|tell me now|what'?s (?:wrong|going on)|how serious|is it serious|severity|diagnose)\b",
|
| 826 |
+
re.I,
|
| 827 |
+
)
|
| 828 |
+
_PLEASANTRY = re.compile(r"^\s*(hi|hello|hey|hiya|good (?:morning|afternoon|evening)|thanks?|thank you|ok|okay|yes|no|yep|nope)\W*$", re.I)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def _uncovered_topics(all_user_text, assistant_text):
|
| 832 |
+
done_by_user = {t for t, rx, _ in TOPIC_QUESTIONS if re.search(rx, all_user_text, re.I)}
|
| 833 |
+
out = []
|
| 834 |
+
for t, rx, q in TOPIC_QUESTIONS:
|
| 835 |
+
if t in done_by_user:
|
| 836 |
+
continue
|
| 837 |
+
out.append((t, q))
|
| 838 |
+
return out
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
def _topic_tags(assistant_texts):
|
| 842 |
+
"""Which topics the assistant already asked about (via hidden marker comments)."""
|
| 843 |
+
tags = set()
|
| 844 |
+
for a in assistant_texts:
|
| 845 |
+
for m in re.finditer(r"<!--asked:([a-z,]+)-->", a or ""):
|
| 846 |
+
tags.update(m.group(1).split(","))
|
| 847 |
+
return tags
|
| 848 |
+
|
| 849 |
|
| 850 |
+
def offline_chat_reply(user_texts, assistant_texts, current_text, preds=None, failure_note=""):
|
| 851 |
+
"""Produce the next chat message with no LLM.
|
| 852 |
|
| 853 |
+
user_texts: earlier user messages (strings); assistant_texts: earlier replies;
|
| 854 |
+
current_text: the message being answered now; preds: classifier output or None.
|
| 855 |
+
"""
|
| 856 |
+
all_user = " \n".join(list(user_texts) + [current_text or ""]).strip()
|
| 857 |
+
turn = len(user_texts) + 1
|
| 858 |
+
head = f"π **{OFFLINE_TAG}** β the AI chat models are unavailable right now, so I'm using my built-in triage rules instead. I can't match an AI's free-text understanding, so I'll ask structured questions and lean cautious.\n\n" if turn == 1 else ""
|
| 859 |
+
|
| 860 |
+
# 1. emergencies take priority at any turn
|
| 861 |
+
emergencies = detect_emergency(all_user)
|
| 862 |
+
if emergencies:
|
| 863 |
+
res = run_offline_assessment(all_user, preds)
|
| 864 |
+
return head + res["text"]
|
| 865 |
+
|
| 866 |
+
already_assessed = any("Severity:" in (a or "") and "Most consistent with" in (a or "") for a in assistant_texts)
|
| 867 |
+
asked = _topic_tags(assistant_texts)
|
| 868 |
+
uncovered = [(t, q) for t, q in _uncovered_topics(all_user, "") if t not in asked]
|
| 869 |
+
|
| 870 |
+
# Greeting / empty first message
|
| 871 |
+
if _PLEASANTRY.match(current_text or "") and turn == 1 and not preds:
|
| 872 |
+
return (head + "Hello! Tell me what you're noticing on your skin β where it is, how long it's been there, and how it looks or feels. "
|
| 873 |
+
"You can also attach a photo with the π button.\n\n<!--asked:where,when-->")
|
| 874 |
+
|
| 875 |
+
wants_now = bool(_ASSESS_REQUEST.search(current_text or ""))
|
| 876 |
+
quick = run_offline_assessment(all_user, preds)
|
| 877 |
+
enough = (
|
| 878 |
+
quick["rank"] == 2 and bool(detect_flags(all_user))
|
| 879 |
+
or wants_now
|
| 880 |
+
or turn >= MIN_ROUNDS_BEFORE_ASSESSMENT + 1
|
| 881 |
+
or (turn >= MIN_ROUNDS_BEFORE_ASSESSMENT and (not uncovered or len(uncovered) <= 3))
|
| 882 |
+
or not uncovered
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
if already_assessed and not wants_now:
|
| 886 |
+
# user keeps talking after an assessment: refresh it with the new info
|
| 887 |
+
return head + "Thanks β here's an updated read with that added:\n\n" + quick["text"]
|
| 888 |
+
|
| 889 |
+
if enough:
|
| 890 |
+
return head + quick["text"]
|
| 891 |
+
|
| 892 |
+
# ask next (up to 2) questions, skipping anything covered
|
| 893 |
+
nxt = uncovered[:2]
|
| 894 |
+
ack = ""
|
| 895 |
+
if turn > 1:
|
| 896 |
+
ack = "Thanks, that helps. "
|
| 897 |
+
elif preds:
|
| 898 |
+
ack = "Thanks for the photo β I've run it through the image classifier. "
|
| 899 |
+
body = ack + ("A couple more questions so I can narrow this down:\n\n" if len(nxt) > 1 else "One more question:\n\n")
|
| 900 |
+
body += "\n".join(f"{i+1}. {q}" for i, (_, q) in enumerate(nxt))
|
| 901 |
+
body += f"\n\n<!--asked:{','.join(t for t, _ in nxt)}-->"
|
| 902 |
+
return head + body
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
# ---------------------------------------------------------------------------
|
| 906 |
+
# Image helpers
|
| 907 |
+
# ---------------------------------------------------------------------------
|
| 908 |
def classify_image(image):
|
| 909 |
"""Run the primary classifier and return (preds, formatted_lines). If the top
|
| 910 |
prediction looks like a mixed/ambiguous pigmented-lesion label and a second
|
|
|
|
| 933 |
|
| 934 |
|
| 935 |
def build_classifier_context(preds):
|
|
|
|
| 936 |
parts = []
|
| 937 |
for p in preds[:4]:
|
| 938 |
label = p["label"]
|
| 939 |
if label.startswith("[lesion-model]"):
|
|
|
|
| 940 |
bare = label.replace("[lesion-model] ", "")
|
| 941 |
tier = classify_tier(bare)
|
| 942 |
parts.append(f"{label} ({p['score']*100:.1f}%, second-opinion, {tier})")
|
|
|
|
| 947 |
return "Image classifier findings for your use (do not read these percentages verbatim): " + "; ".join(parts)
|
| 948 |
|
| 949 |
|
| 950 |
+
def _model_footer(model_used, tried_failed=None):
|
| 951 |
+
note = f"Answered by `{model_used}`"
|
| 952 |
+
if tried_failed:
|
| 953 |
+
note += f" (switched automatically after {len(tried_failed)} unavailable: " + ", ".join(f"`{m}`" for m, _ in tried_failed) + ")"
|
| 954 |
+
return f"\n\n<sub>{note}</sub>"
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def _failed_before(selected, model_used):
|
| 958 |
+
"""Models listed ahead of the one that answered (these failed or were skipped)."""
|
| 959 |
+
sel = _clean_selection(selected)
|
| 960 |
+
return [(m, "") for m in sel[: sel.index(model_used)]] if model_used in sel else []
|
| 961 |
+
|
| 962 |
+
|
| 963 |
# ---------------------------------------------------------------------------
|
| 964 |
# Image diagnosis tab (single-shot: upload -> classify -> explain)
|
| 965 |
# ---------------------------------------------------------------------------
|
| 966 |
@spaces.GPU
|
| 967 |
+
def diagnose_image(image, selected_models=None):
|
| 968 |
if image is None:
|
| 969 |
return "Please upload an image or pick one of the test images first."
|
| 970 |
|
|
|
|
| 976 |
lines = ["### π¬ Classifier prediction\n"] + lines_list
|
| 977 |
lines.append(f"\n{severity_line(preds[0]['label'])}")
|
| 978 |
|
| 979 |
+
context = build_classifier_context(preds)
|
| 980 |
+
prompt = (
|
| 981 |
+
f"{context}\n\n"
|
| 982 |
+
"The user just uploaded a single image with no conversation yet. Give a short "
|
| 983 |
+
"preliminary assessment following your instructions: plain-language explanation of "
|
| 984 |
+
"the top finding(s), an explicit Low/Medium/High severity call, and a brief natural "
|
| 985 |
+
"mention that an in-person exam is what actually confirms things. Note that without "
|
| 986 |
+
"any conversation history you have less context than usual β you can still give your "
|
| 987 |
+
"best read, but you may want to suggest the Chat Assistant for a fuller picture if the "
|
| 988 |
+
"case seems ambiguous. Keep it to 5-7 sentences."
|
| 989 |
+
)
|
| 990 |
+
try:
|
| 991 |
+
explanation, used = chat_completion(
|
| 992 |
+
[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
|
| 993 |
+
max_tokens=300,
|
| 994 |
+
models=selected_models,
|
| 995 |
)
|
| 996 |
+
lines.append(f"\n### π€ Assessment\n{explanation}")
|
| 997 |
+
lines.append(_model_footer(used, _failed_before(selected_models, used)))
|
| 998 |
+
except AllModelsFailed as e:
|
| 999 |
+
lines.append(f"\n### π Assessment ({OFFLINE_TAG})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1000 |
lines.append(
|
| 1001 |
+
"_No AI chat model could be reached, so this assessment comes from the built-in "
|
| 1002 |
+
"rule engine using the classifier result._\n"
|
| 1003 |
)
|
| 1004 |
+
lines.append(offline_assessment("", preds))
|
| 1005 |
+
lines.append(f"\n<sub>Models tried: {_attempts_note(e.attempts) or 'none selected / no HF_TOKEN set'}</sub>")
|
| 1006 |
|
| 1007 |
lines.append(
|
| 1008 |
"\n---\n_Tip: use the **Chat Assistant** tab for a fuller triage conversation β "
|
|
|
|
| 1014 |
# ---------------------------------------------------------------------------
|
| 1015 |
# Chat tab β multimodal, multi-turn triage
|
| 1016 |
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 1017 |
def _extract_text_and_image(message):
|
|
|
|
| 1018 |
if isinstance(message, dict):
|
| 1019 |
text = message.get("text", "") or ""
|
| 1020 |
files = message.get("files") or []
|
| 1021 |
+
first = files[0] if files else None
|
| 1022 |
+
image_path = first.get("path") if isinstance(first, dict) else first
|
| 1023 |
return text, image_path
|
| 1024 |
return str(message), None
|
| 1025 |
|
|
|
|
| 1029 |
|
| 1030 |
|
| 1031 |
def _stage_note(user_turn_count):
|
|
|
|
|
|
|
|
|
|
| 1032 |
if user_turn_count < MIN_ROUNDS_BEFORE_ASSESSMENT:
|
| 1033 |
return (
|
| 1034 |
f"[Internal note β not from the user: this is exchange {user_turn_count} of at least "
|
|
|
|
| 1046 |
)
|
| 1047 |
|
| 1048 |
|
| 1049 |
+
_COMMENT_RE = re.compile(r"<!--.*?-->", re.S)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1050 |
|
|
|
|
| 1051 |
|
| 1052 |
+
def _history_to_pairs(history):
|
| 1053 |
+
"""Normalise Gradio history (messages or tuples) to a list of (role, plain_text)."""
|
| 1054 |
+
out = []
|
| 1055 |
+
for turn in history or []:
|
| 1056 |
if isinstance(turn, dict):
|
| 1057 |
+
role, content = turn.get("role"), turn.get("content")
|
| 1058 |
+
if isinstance(content, (tuple, list)) or isinstance(content, dict):
|
| 1059 |
+
continue # file attachments in history
|
| 1060 |
+
if isinstance(content, str) and role in ("user", "assistant"):
|
| 1061 |
+
out.append((role, content))
|
| 1062 |
else:
|
| 1063 |
+
u, b = turn
|
| 1064 |
+
if isinstance(u, str):
|
| 1065 |
+
out.append(("user", u))
|
| 1066 |
+
if isinstance(b, str) and b:
|
| 1067 |
+
out.append(("assistant", b))
|
| 1068 |
+
cleaned = []
|
| 1069 |
+
for role, c in out:
|
| 1070 |
+
c = _COMMENT_RE.sub("", c) if role == "assistant" else c
|
| 1071 |
+
cleaned.append((role, _strip_footer(c) if role == "assistant" else c))
|
| 1072 |
+
return cleaned
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def chat_respond(message, history, selected_models=None):
|
| 1076 |
+
text, image_path = _extract_text_and_image(message)
|
| 1077 |
+
pairs = _history_to_pairs(history)
|
| 1078 |
|
| 1079 |
+
# image analysis (local; independent of the chat models)
|
| 1080 |
+
preds, img_note = None, ""
|
| 1081 |
if image_path:
|
| 1082 |
try:
|
| 1083 |
+
preds, _ = classify_image(Image.open(image_path))
|
|
|
|
|
|
|
|
|
|
| 1084 |
except Exception as e:
|
| 1085 |
+
img_note = f"(Image analysis failed: {e})"
|
| 1086 |
+
# classifier output from an earlier turn is carried inside the chat history
|
| 1087 |
+
# itself (hidden comment), so nothing is shared between users/sessions
|
| 1088 |
+
if preds is None:
|
| 1089 |
+
preds = _preds_from_history(history)
|
| 1090 |
+
|
| 1091 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 1092 |
+
messages += [{"role": r, "content": c} for r, c in pairs]
|
| 1093 |
+
|
| 1094 |
+
user_content = text
|
| 1095 |
+
if preds and image_path:
|
| 1096 |
+
user_content = f"{build_classifier_context(preds)}\n\nUser's message: {text or '(no message, just shared an image)'}"
|
| 1097 |
+
elif img_note:
|
| 1098 |
+
user_content = f"{img_note}\n\nUser's message: {text}"
|
| 1099 |
|
|
|
|
| 1100 |
current_turn_count = _count_user_turns(messages) + 1
|
| 1101 |
+
messages.append({"role": "user", "content": f"{_stage_note(current_turn_count)}\n\n{user_content}"})
|
|
|
|
| 1102 |
|
| 1103 |
try:
|
| 1104 |
+
reply, used = chat_completion(messages, max_tokens=500, models=selected_models)
|
| 1105 |
+
result = reply + _model_footer(used, _failed_before(selected_models, used))
|
| 1106 |
+
except AllModelsFailed as e:
|
| 1107 |
+
user_texts = [c for r, c in pairs if r == "user"]
|
| 1108 |
+
asst_texts = [c for r, c in pairs if r == "assistant"]
|
| 1109 |
+
# restore hidden asked-topic markers (stripped above for the LLM path)
|
| 1110 |
+
asst_raw = [c for r, c in _raw_assistant(history)]
|
| 1111 |
+
reply = offline_chat_reply(user_texts, asst_raw or asst_texts, text, preds)
|
| 1112 |
+
first = e.attempts[0] if e.attempts else None
|
| 1113 |
+
why = f"{len(e.attempts)} model(s) tried; first error: `{first[0]}` β {first[1]}" if first else "no model available"
|
| 1114 |
+
result = reply + f"\n\n<sub>All selected chat models failed ({why}). Offline mode is active; I retry the models on every message.</sub>"
|
| 1115 |
+
|
| 1116 |
+
if preds:
|
| 1117 |
+
result += _preds_comment(preds)
|
| 1118 |
+
return result
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
import json as _json
|
| 1122 |
+
|
| 1123 |
+
_PREDS_RE = re.compile(r"<!--preds:(.*?)-->", re.S)
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
def _preds_comment(preds):
|
| 1127 |
+
slim = [{"label": p["label"], "score": round(float(p["score"]), 4)} for p in preds[:6]]
|
| 1128 |
+
return "<!--preds:" + _json.dumps(slim).replace("--", "- -") + "-->"
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
def _preds_from_history(history):
|
| 1132 |
+
found = None
|
| 1133 |
+
for _, c in _raw_assistant(history):
|
| 1134 |
+
m = _PREDS_RE.search(c or "")
|
| 1135 |
+
if m:
|
| 1136 |
+
try:
|
| 1137 |
+
found = _json.loads(m.group(1))
|
| 1138 |
+
except Exception:
|
| 1139 |
+
pass
|
| 1140 |
+
return found
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def _raw_assistant(history):
|
| 1144 |
+
out = []
|
| 1145 |
+
for turn in history or []:
|
| 1146 |
+
if isinstance(turn, dict):
|
| 1147 |
+
if turn.get("role") == "assistant" and isinstance(turn.get("content"), str):
|
| 1148 |
+
out.append(("assistant", turn["content"]))
|
| 1149 |
+
else:
|
| 1150 |
+
if isinstance(turn[1], str) and turn[1]:
|
| 1151 |
+
out.append(("assistant", turn[1]))
|
| 1152 |
+
return out
|
| 1153 |
|
| 1154 |
|
| 1155 |
# ---------------------------------------------------------------------------
|
|
|
|
| 1158 |
ASSETS_DIR = "assets"
|
| 1159 |
|
| 1160 |
|
|
|
|
|
|
|
| 1161 |
def load_performance_reports():
|
| 1162 |
+
"""Scan assets/ for (1) full reports: *_metrics.json + confusion matrix + same-prefix
|
| 1163 |
+
images, and (2) image-only reports: any *_confusion_matrix image without a metrics.json."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1164 |
import json
|
| 1165 |
+
|
| 1166 |
reports = []
|
| 1167 |
if not os.path.isdir(ASSETS_DIR):
|
| 1168 |
return reports
|
| 1169 |
all_files = sorted(os.listdir(ASSETS_DIR))
|
| 1170 |
+
claimed = set()
|
| 1171 |
+
|
|
|
|
| 1172 |
for fname in all_files:
|
| 1173 |
if not fname.endswith("_metrics.json"):
|
| 1174 |
continue
|
|
|
|
| 1178 |
data = json.load(f)
|
| 1179 |
except Exception:
|
| 1180 |
continue
|
| 1181 |
+
|
| 1182 |
image_path = None
|
| 1183 |
for ext in (".png", ".jpg", ".jpeg"):
|
| 1184 |
candidate = os.path.join(ASSETS_DIR, f"{prefix}_confusion_matrix{ext}")
|
|
|
|
| 1186 |
image_path = candidate
|
| 1187 |
claimed.add(f"{prefix}_confusion_matrix{ext}")
|
| 1188 |
break
|
| 1189 |
+
|
| 1190 |
extra_images = []
|
| 1191 |
for other in all_files:
|
| 1192 |
if not other.startswith(prefix + "_") or not other.lower().endswith((".png", ".jpg", ".jpeg")):
|
|
|
|
| 1196 |
label = other[len(prefix) + 1:].rsplit(".", 1)[0].replace("_", " ").strip().title()
|
| 1197 |
extra_images.append({"path": os.path.join(ASSETS_DIR, other), "label": label})
|
| 1198 |
claimed.add(other)
|
| 1199 |
+
|
| 1200 |
reports.append({"data": data, "image_path": image_path, "extra_images": extra_images})
|
| 1201 |
+
|
|
|
|
|
|
|
| 1202 |
seen_prefixes = set()
|
| 1203 |
for fname in all_files:
|
| 1204 |
if fname in claimed or not fname.lower().endswith((".png", ".jpg", ".jpeg")):
|
| 1205 |
continue
|
| 1206 |
+
idx = fname.lower().find("_confusion_matrix")
|
|
|
|
| 1207 |
if idx == -1:
|
| 1208 |
+
continue
|
| 1209 |
prefix = fname[:idx]
|
| 1210 |
if prefix in seen_prefixes:
|
| 1211 |
continue
|
| 1212 |
seen_prefixes.add(prefix)
|
| 1213 |
+
|
| 1214 |
extra_images = []
|
| 1215 |
for other in all_files:
|
| 1216 |
if other == fname or other in claimed or not other.startswith(prefix + "_"):
|
|
|
|
| 1220 |
label = other[len(prefix) + 1:].rsplit(".", 1)[0].replace("_", " ").strip().title()
|
| 1221 |
extra_images.append({"path": os.path.join(ASSETS_DIR, other), "label": label})
|
| 1222 |
claimed.add(other)
|
| 1223 |
+
|
|
|
|
| 1224 |
reports.append({
|
| 1225 |
+
"data": {"model_name": prefix.replace("_", " ").strip().title() or "Model", "image_only": True},
|
| 1226 |
"image_path": os.path.join(ASSETS_DIR, fname),
|
| 1227 |
"extra_images": extra_images,
|
| 1228 |
})
|
|
|
|
|
|
|
| 1229 |
|
| 1230 |
+
return reports
|
| 1231 |
|
| 1232 |
|
| 1233 |
def format_performance_markdown(report):
|
| 1234 |
data = report["data"]
|
| 1235 |
lines = [f"### {data.get('model_name', 'Model')}"]
|
| 1236 |
+
|
| 1237 |
if data.get("image_only"):
|
| 1238 |
lines.append(
|
| 1239 |
"_Charts available β metrics summary not uploaded yet. Add a matching "
|
| 1240 |
"`*_metrics.json` to this prefix for the full accuracy/F1/per-class table._"
|
| 1241 |
)
|
| 1242 |
return "\n".join(lines)
|
| 1243 |
+
|
| 1244 |
acc = data.get("accuracy")
|
| 1245 |
f1m = data.get("f1_macro")
|
| 1246 |
if acc is not None:
|
| 1247 |
lines.append(f"**Accuracy:** {acc*100:.1f}% Β· **Macro F1:** {f1m*100:.1f}%" if f1m is not None else f"**Accuracy:** {acc*100:.1f}%")
|
| 1248 |
+
|
| 1249 |
per_class = data.get("per_class", {})
|
| 1250 |
if per_class:
|
| 1251 |
lines.append("\n| Class | Precision | Recall | F1 | Support |")
|
|
|
|
| 1255 |
f"| {cls} | {m.get('precision', 0)*100:.1f}% | {m.get('recall', 0)*100:.1f}% "
|
| 1256 |
f"| {m.get('f1', 0)*100:.1f}% | {int(m.get('support', 0))} |"
|
| 1257 |
)
|
| 1258 |
+
|
| 1259 |
notes = data.get("notes")
|
| 1260 |
if notes:
|
| 1261 |
lines.append(f"\n_Note: {notes}_")
|
| 1262 |
+
|
| 1263 |
return "\n".join(lines)
|
| 1264 |
|
| 1265 |
+
|
| 1266 |
ABOUT_MARKDOWN = f"""
|
| 1267 |
## About this project
|
|
|
|
| 1268 |
A research/portfolio demo exploring how far an image classifier + LLM chat
|
| 1269 |
assistant can go toward useful skin-condition triage β while being explicit
|
| 1270 |
about what it isn't: a validated medical device.
|
|
|
|
| 1271 |
### What's inside
|
| 1272 |
- **Quick Image Check** β upload a photo, get a classifier prediction plus
|
| 1273 |
an LLM-generated plain-language assessment with an explicit Low/Medium/High
|
|
|
|
| 1276 |
evolution, symptoms, triggers, and history before giving a more targeted
|
| 1277 |
preliminary read than a single photo alone could support.
|
| 1278 |
- **Model Performance** β the actual test-set metrics for whichever
|
| 1279 |
+
fine-tuned model(s) are currently backing this app.
|
|
|
|
|
|
|
| 1280 |
### Models
|
| 1281 |
+
- **Image classifier:** configurable via `IMAGE_MODEL_ID`.
|
| 1282 |
+
- **Optional second-opinion lesion model:** `LESION_MODEL_ID`.
|
| 1283 |
+
- **Chat models (multi-select):** pick one or several in the dropdown. They
|
| 1284 |
+
are tried in the order listed; if one fails the app switches to the next
|
| 1285 |
+
automatically. Defaults come from the `CHAT_MODELS` variable.
|
| 1286 |
+
- **Offline assistant:** if *every* selected chat model fails, the app keeps
|
| 1287 |
+
working with a built-in rule-based triage engine (no network, no LLM). It
|
| 1288 |
+
asks structured follow-up questions, matches symptoms against ~30 skin
|
| 1289 |
+
conditions, blends in the image classifier result, and always gives a
|
| 1290 |
+
Low/Medium/High severity. It is deliberately cautious β when unsure it
|
| 1291 |
+
rates *higher*, not lower. It cannot match an LLM's free-text understanding,
|
| 1292 |
+
so unusual descriptions may get a generic answer.
|
| 1293 |
### Severity levels
|
| 1294 |
- π΄ **High** β cancer-related, ambiguous-but-could-be-serious, systemic/
|
| 1295 |
autoimmune, or red-flag symptoms present. See a doctor soon.
|
|
|
|
| 1297 |
(infections, infestations). See a doctor, not an emergency.
|
| 1298 |
- π’ **Low** β typically manageable with general skin care. Doctor visit
|
| 1299 |
optional, especially if unsure or it's not improving.
|
| 1300 |
+
### Known limitations
|
|
|
|
| 1301 |
- **Not clinically validated.** Benchmark accuracy on a public dataset is
|
| 1302 |
not the same as real-world diagnostic reliability.
|
| 1303 |
+
- **Dataset label limitations.** Some taxonomies combine melanoma with
|
| 1304 |
+
benign moles under one label β the app defaults that to High severity.
|
|
|
|
| 1305 |
- **Skin-tone representation.** Public dermatology datasets skew toward
|
| 1306 |
+
lighter skin tones; performance elsewhere is unverified.
|
|
|
|
| 1307 |
- **No clinical validation, IRB review, or regulatory clearance** has been
|
| 1308 |
done. This should inform, not replace, professional care.
|
|
|
|
| 1309 |
{PAGE_DISCLAIMER}
|
| 1310 |
"""
|
| 1311 |
|
|
|
|
| 1326 |
gr.Markdown("# π©Ί Skin Disease Detection")
|
| 1327 |
gr.Markdown(f"_{PAGE_DISCLAIMER}_")
|
| 1328 |
|
| 1329 |
+
model_select = gr.Dropdown(
|
| 1330 |
+
choices=CHAT_MODELS,
|
| 1331 |
+
value=list(CHAT_MODELS),
|
| 1332 |
+
multiselect=True,
|
| 1333 |
+
allow_custom_value=True,
|
| 1334 |
+
label="Chat models (tried in the order shown; the app switches automatically if one fails)",
|
| 1335 |
+
info="Remove models you don't want, or type a custom model id and press Enter. "
|
| 1336 |
+
"If all of them fail, the built-in offline assistant takes over.",
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
with gr.Tab("π· Quick Image Check"):
|
| 1340 |
with gr.Row():
|
| 1341 |
with gr.Column():
|
|
|
|
| 1350 |
analyze_btn = gr.Button("Analyze image", variant="primary")
|
| 1351 |
with gr.Column():
|
| 1352 |
result_md = gr.Markdown()
|
| 1353 |
+
analyze_btn.click(diagnose_image, inputs=[img_in, model_select], outputs=result_md)
|
| 1354 |
|
| 1355 |
with gr.Tab("π¬ Chat Assistant"):
|
| 1356 |
gr.ChatInterface(
|
| 1357 |
fn=chat_respond,
|
| 1358 |
multimodal=True,
|
| 1359 |
+
additional_inputs=[model_select],
|
| 1360 |
description=(
|
| 1361 |
"Talk through what you're noticing, and optionally attach a photo (π). "
|
| 1362 |
"The assistant will ask several follow-up questions before giving a preliminary "
|
|
|
|
| 1388 |
|
| 1389 |
gr.Markdown(
|
| 1390 |
"---\nBuilt with π€ Transformers + Gradio. "
|
| 1391 |
+
f"Image model: `{IMAGE_MODEL_ID}` Β· Default chat model: `{CHAT_MODEL_ID}`"
|
| 1392 |
)
|
| 1393 |
|
| 1394 |
if __name__ == "__main__":
|
| 1395 |
+
demo.launch()
|