Pro-Coder commited on
Commit
6cd0db0
·
verified ·
1 Parent(s): 38d3060

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +481 -952
app.py CHANGED
@@ -1,29 +1,22 @@
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,52 +27,52 @@ from transformers import pipeline
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 "
@@ -87,12 +80,17 @@ PAGE_DISCLAIMER = (
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,15 +102,34 @@ PROMPT_DOCTOR_KEYWORDS = [
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"},
110
- "prompt_doctor_visit": {"label": "Medium", "emoji": "🟡", "note": "needs a proper diagnosis/prescription, not an emergency"},
111
- "general_care": {"label": "Low", "emoji": "🟢", "note": "typically manageable with general skin care"},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  }
113
 
114
 
115
  def classify_tier(label):
 
116
  l = label.lower()
117
  for kw in URGENT_KEYWORDS:
118
  if kw in l:
@@ -123,11 +140,18 @@ def classify_tier(label):
123
  return "general_care"
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.",
@@ -137,8 +161,21 @@ KNOWN_DESCRIPTIONS = {
137
  "melanocytic nevi": "Ordinary moles.",
138
  "vascular lesions": "Blood-vessel-related marks such as angiomas.",
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,6 +187,7 @@ Have a real back-and-forth, one or two questions at a time. Aim to gather a full
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,13 +196,15 @@ Once you have real depth of context, give a clear, specific preliminary assessme
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,6 +221,7 @@ def get_classifier():
181
 
182
 
183
  def get_lesion_classifier():
 
184
  global _lesion_classifier
185
  if not LESION_MODEL_ID:
186
  return None
@@ -192,730 +233,191 @@ def get_lesion_classifier():
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
911
  lesion-specific model is configured, also run that for a second opinion."""
912
  clf = get_classifier()
913
  preds = clf(image, top_k=5)
 
914
  lines = []
915
  for p in preds:
916
  label = p["label"]
917
  score = p["score"] * 100
918
- desc = KNOWN_DESCRIPTIONS.get(label.lower(), "")
919
  desc_txt = f" \n _{desc}_" if desc else ""
920
  lines.append(f"- **{label}** — {score:.1f}%{desc_txt}")
921
 
@@ -924,7 +426,12 @@ def classify_image(image):
924
  lesion_clf = get_lesion_classifier()
925
  if lesion_clf is not None:
926
  lesion_preds = lesion_clf(image, top_k=3)
927
- lines.append("\n_Second opinion from a lesion-specific model (melanoma is a distinct label here):_")
 
 
 
 
 
928
  for p in lesion_preds:
929
  lines.append(f"- **{p['label']}** — {p['score']*100:.1f}%")
930
  preds = preds + [{"label": f"[lesion-model] {p['label']}", "score": p["score"]} for p in lesion_preds]
@@ -933,10 +440,12 @@ def classify_image(image):
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,66 +456,64 @@ def build_classifier_context(preds):
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
 
971
  try:
972
- preds, lines_list = classify_image(image)
973
  except Exception as e:
974
  return f"**Model error:** {e}\n\nMake sure `IMAGE_MODEL_ID` is a valid image-classification model."
975
 
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 — "
1009
- "it can ask follow-up questions and give a more tailored read._"
 
1010
  )
1011
  return "\n".join(lines)
1012
 
@@ -1014,12 +521,15 @@ def diagnose_image(image, selected_models=None):
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,6 +539,9 @@ def _count_user_turns(messages):
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,110 +559,68 @@ def _stage_note(user_turn_count):
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
  # ---------------------------------------------------------------------------
@@ -1159,16 +630,25 @@ 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
@@ -1199,13 +679,16 @@ def load_performance_reports():
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
@@ -1221,8 +704,9 @@ def load_performance_reports():
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
  })
@@ -1237,7 +721,9 @@ def format_performance_markdown(report):
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
 
@@ -1265,9 +751,11 @@ def format_performance_markdown(report):
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,20 +764,21 @@ about what it isn't: a validated medical device.
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,16 +786,55 @@ about what it isn't: a validated medical device.
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
 
1312
 
@@ -1322,50 +850,47 @@ if os.path.isdir(EXAMPLES_DIR):
1322
  if f.lower().endswith((".jpg", ".jpeg", ".png"))
1323
  ]
1324
 
1325
- with gr.Blocks(title="Skin Disease Detection — Demo") as demo:
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():
1342
- img_in = gr.Image(type="pil", label="Upload a skin image")
 
 
 
 
1343
  if example_images:
1344
- gr.Examples(examples=example_images, inputs=img_in, label="Or try a test image")
1345
  else:
1346
  gr.Markdown(
1347
  "_No bundled test images found. Run `scripts/download_examples.py` "
1348
  "before deploying, or just upload your own image._"
1349
  )
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 "
1363
  "read with a Low/Medium/High severity call — the more you share, the more "
1364
- "targeted that read can be."
 
 
 
 
1365
  ),
1366
  )
1367
 
1368
- with gr.Tab("📊 Model Performance"):
1369
  performance_reports = load_performance_reports()
1370
  if not performance_reports:
1371
  gr.Markdown(
@@ -1373,23 +898,27 @@ with gr.Blocks(title="Skin Disease Detection — Demo") as demo:
1373
  "Run either fine-tuning notebook in this repo, then download the "
1374
  "`*_metrics.json` and `*_confusion_matrix.png` files it produces and place "
1375
  "them in this Space's `assets/` folder. This tab picks them up automatically "
1376
- "on the next restart."
 
 
 
1377
  )
1378
  else:
1379
  for report in performance_reports:
1380
  gr.Markdown(format_performance_markdown(report))
1381
  if report["image_path"]:
1382
- gr.Image(value=report["image_path"], label="Confusion matrix (test set)", show_label=True)
1383
  for extra in report.get("extra_images", []):
1384
- gr.Image(value=extra["path"], label=extra["label"], show_label=True)
1385
 
1386
- with gr.Tab("ℹ️ About"):
1387
  gr.Markdown(ABOUT_MARKDOWN)
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()
 
1
  """
2
+ Skin Disease Detection — Demo
3
+ ------------------------------
4
+ A Gradio app for Hugging Face Spaces with two tabs:
5
+ 1. Image Diagnosis — upload (or pick a test image) and get a classifier
6
+ prediction plus a plain-language, urgency-aware explanation.
7
+ 2. Chat Assistant — a multi-turn triage chatbot. It can accept an image,
8
+ asks the kind of follow-up questions a real triage intake would, and
9
+ after enough context gives a preliminary assessment with urgency-tiered
10
+ guidance.
11
+
12
+ IMPORTANT: This remains a research/portfolio project, not a validated
13
+ medical device. It has not been clinically evaluated or regulatory
14
+ cleared. It should never be the sole basis for a health decision — that
15
+ framing shows up once, clearly, rather than as a repeated warning block
16
+ after every message, but it's still true and still matters.
 
 
 
 
 
17
  """
18
 
19
  import os
 
 
20
 
21
  import gradio as gr
22
  import spaces
 
27
  # ---------------------------------------------------------------------------
28
  # Config — override any of these via Space "Variables and secrets"
29
  # ---------------------------------------------------------------------------
30
+ IMAGE_MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "Anwarkh1/Skin_Cancer-Image_Classification").strip()
31
+ # Hugging Face retired the old api-inference.huggingface.co Serverless API in
32
+ # favor of the "Inference Providers" router (OpenAI-compatible). Any chat
33
+ # model listed at https://huggingface.co/models?inference_provider=hf-inference
34
+ # works here.
35
+ CHAT_MODEL_ID = os.environ.get("CHAT_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct").strip()
36
+ # If CHAT_MODEL_ID becomes unavailable (providers rotate their catalogs over
37
+ # time -- see chat_completion() below), these are tried next, in order.
38
+ # Override via a comma-separated CHAT_MODEL_FALLBACKS variable if needed.
39
+ # (mistralai/Mistral-7B-Instruct-v0.3 was tried and confirmed NOT to work via
40
+ # the router -- "not a chat model" -- so it's deliberately left out here.)
41
+ CHAT_MODEL_FALLBACKS = [
42
+ m.strip()
43
+ for m in os.environ.get(
44
+ "CHAT_MODEL_FALLBACKS",
45
+ "openai/gpt-oss-120b,"
46
+ "openai/gpt-oss-20b,"
47
+ "deepseek-ai/DeepSeek-V3-0324,"
48
+ "meta-llama/Llama-3.1-8B-Instruct,"
49
+ "meta-llama/Llama-3.3-70B-Instruct,"
50
+ "Qwen/Qwen2.5-72B-Instruct",
51
+ ).split(",")
52
+ if m.strip()
53
+ ]
54
  HF_TOKEN = os.environ.get("HF_TOKEN") # add as a Space SECRET to enable the chatbot
55
  HF_TOKEN = HF_TOKEN.strip() if HF_TOKEN else HF_TOKEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Optional: run your own fine-tuned chatbot LOCALLY instead of calling the
58
+ # router. HF's shared Inference Providers router only serves models a
59
+ # provider has chosen to host -- it can't serve a custom LoRA adapter you
60
+ # trained yourself (see finetune_chatbot.ipynb). Setting both of these makes
61
+ # the app load and run that model directly on the Space's own GPU instead.
62
+ # Leave either unset to keep using the router-based path (the default).
63
+ LOCAL_CHAT_MODEL_ID = os.environ.get("LOCAL_CHAT_MODEL_ID", "").strip()
64
+ LOCAL_LORA_ADAPTER_ID = os.environ.get("LOCAL_LORA_ADAPTER_ID", "").strip()
65
+ USE_LOCAL_CHAT_MODEL = bool(LOCAL_CHAT_MODEL_ID and LOCAL_LORA_ADAPTER_ID)
66
+ ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
67
+ # Groq (OpenAI-compatible, free tier with rate limits): add GROQ_API_KEY as a Space SECRET.
68
+ # Groq models are tried first when the key is set; any failure (429 rate limit, bad key,
69
+ # timeout, unknown model) moves on to the Hugging Face path below.
70
+ GROQ_API_KEY = (os.environ.get("GROQ_API_KEY") or "").strip()
71
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
72
+ GROQ_MODELS = [m.strip() for m in os.environ.get(
73
+ "GROQ_MODELS", "openai/gpt-oss-120b,openai/gpt-oss-20b,llama-3.3-70b-versatile,llama-3.1-8b-instant"
74
+ ).split(",") if m.strip()]
75
+ CHAT_ENABLED = bool(HF_TOKEN or GROQ_API_KEY)
76
 
77
  PAGE_DISCLAIMER = (
78
  "This tool is a research/portfolio project, not a medical device. It hasn't "
 
80
  "before a real appointment — not as a substitute for one."
81
  )
82
 
83
+ # Optional second classifier specifically for pigmented-lesion cases (HAM10000-based,
84
+ # where melanoma is its own clean label). Useful because broader taxonomies like
85
+ # DermNet lump "Melanoma Skin Cancer, Nevi and Moles" into one label — this lets a
86
+ # mole/nevus-flagged image get a second, more specific opinion. Leave unset to disable.
87
  LESION_MODEL_ID = os.environ.get("LESION_MODEL_ID", "").strip()
88
 
89
  # ---------------------------------------------------------------------------
90
+ # Urgency tiering — keyword-based rather than an exact-match label dict, so it
91
+ # works across different classifier taxonomies (the original 7-class HAM10000
92
+ # labels, the 23-class DermNet labels, or any future swap) without needing to
93
+ # hardcode every exact label string. Checked in priority order.
94
  # ---------------------------------------------------------------------------
95
  URGENT_KEYWORDS = [
96
  "melanoma", "malignant", "carcinoma", "actinic keratos",
 
102
  "viral", "herpes", "hpv", "std", "exanthem", "drug eruption",
103
  "impetigo", "bacterial",
104
  ]
105
+ # Anything not matching the above falls through to "general_care" — typically
106
+ # manageable/chronic conditions (acne, eczema, psoriasis, hives, hair loss,
107
+ # benign tumors, common moles, etc.) where general skin-care guidance fits.
108
 
109
  SEVERITY = {
110
+ "urgent": {
111
+ "label": "High", "label_ja": "高",
112
+ "emoji": "🔴",
113
+ "note": "recommend seeing a dermatologist/doctor soon",
114
+ "note_ja": "早めに皮膚科・医師の受診をおすすめします",
115
+ },
116
+ "prompt_doctor_visit": {
117
+ "label": "Medium", "label_ja": "中",
118
+ "emoji": "🟡",
119
+ "note": "needs a proper diagnosis/prescription, not an emergency",
120
+ "note_ja": "緊急ではありませんが、正式な診断・処方が必要です",
121
+ },
122
+ "general_care": {
123
+ "label": "Low", "label_ja": "低",
124
+ "emoji": "🟢",
125
+ "note": "typically manageable with general skin care",
126
+ "note_ja": "一般的なスキンケアで対応できることが多いです",
127
+ },
128
  }
129
 
130
 
131
  def classify_tier(label):
132
+ """Map a classifier label to an urgency tier via keyword matching."""
133
  l = label.lower()
134
  for kw in URGENT_KEYWORDS:
135
  if kw in l:
 
140
  return "general_care"
141
 
142
 
143
+ def severity_line(label, language="English"):
144
+ tier = classify_tier(label)
145
+ s = SEVERITY[tier]
146
+ if language == "日本語":
147
+ return f"{s['emoji']} **重症度:{s['label_ja']}({s['label']})** — {s['note_ja']}"
148
  return f"{s['emoji']} **Severity: {s['label']}** — {s['note']}"
149
 
150
 
151
+ # Friendly one-line descriptions for labels we recognize exactly (both the
152
+ # original 7-class HAM10000 set and common DermNet-style labels). Purely
153
+ # cosmetic — if a label isn't here, the tier-based guidance still works fine
154
+ # without a description. English and Japanese pairs, keyed the same.
155
  KNOWN_DESCRIPTIONS = {
156
  "actinic keratoses": "A rough, scaly patch caused by sun damage.",
157
  "basal cell carcinoma": "The most common type of skin cancer.",
 
161
  "melanocytic nevi": "Ordinary moles.",
162
  "vascular lesions": "Blood-vessel-related marks such as angiomas.",
163
  }
164
+ KNOWN_DESCRIPTIONS_JA = {
165
+ "actinic keratoses": "日光による損傷が原因の、ざらざらした鱗屑状の斑点です。",
166
+ "basal cell carcinoma": "最も一般的な皮膚がんの一種です。",
167
+ "melanoma": "最も深刻な、一般的な皮膚がんの一種です。",
168
+ "benign keratosis-like lesions": "脂漏性角化症や日光黒子など、良性の増殖です。",
169
+ "dermatofibroma": "主に脚にできる、一般的な良性のしこりです。",
170
+ "melanocytic nevi": "一般的なほくろです。",
171
+ "vascular lesions": "血管腫など、血管に関連する良性のマークです。",
172
+ }
173
 
174
  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.
175
+
176
+ LANGUAGE
177
+ You are fully fluent in both English and Japanese. Always respond in the same language the user's most recent message is written in — if they write in Japanese (日本語), respond entirely in natural, fluent Japanese; if they write in English, respond in English. If a conversation switches languages mid-way, follow the switch. Keep medical/technical terms accurate in whichever language you're using rather than leaving them untranslated.
178
+
179
  CONVERSATION STYLE — GO DEEPER BEFORE ASSESSING
180
  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):
181
  - Onset: how long they've had it, how it started
 
187
  - Location and distribution on the body
188
  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.
189
  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.
190
+
191
  GIVING A PRELIMINARY ASSESSMENT
192
  Once you have real depth of context, give a clear, specific preliminary assessment:
193
  - 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.
 
196
  - **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.
197
  - **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.
198
  - 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.
199
+
200
  URGENT SITUATIONS
201
  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.
202
+
203
  Keep replies conversational length — a few sentences for a question, a bit longer for the assessment itself."""
204
 
205
 
206
  # ---------------------------------------------------------------------------
207
+ # Lazy-loaded models (so the Space boots fast and only loads on first use)
208
  # ---------------------------------------------------------------------------
209
  _classifier = None
210
  _lesion_classifier = None
 
221
 
222
 
223
  def get_lesion_classifier():
224
+ """Optional second opinion model for pigmented-lesion cases. Returns None if disabled."""
225
  global _lesion_classifier
226
  if not LESION_MODEL_ID:
227
  return None
 
233
  return _lesion_classifier
234
 
235
 
236
+ _local_chat_model = None
237
+ _local_chat_tokenizer = None
 
 
 
 
238
 
 
 
 
239
 
240
+ def get_local_chat_model():
241
+ """Lazily loads the fine-tuned local chatbot (base model + LoRA adapter),
242
+ 4-bit quantized the same way it was trained (finetune_chatbot.ipynb).
243
+ Only called when USE_LOCAL_CHAT_MODEL is True."""
244
+ global _local_chat_model, _local_chat_tokenizer
245
+ if _local_chat_model is None:
246
+ import torch
247
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
248
+ from peft import PeftModel
249
+
250
+ bnb_config = BitsAndBytesConfig(
251
+ load_in_4bit=True,
252
+ bnb_4bit_quant_type="nf4",
253
+ bnb_4bit_compute_dtype=torch.bfloat16,
254
+ bnb_4bit_use_double_quant=True,
255
+ )
256
+ _local_chat_tokenizer = AutoTokenizer.from_pretrained(LOCAL_CHAT_MODEL_ID)
257
+ if _local_chat_tokenizer.pad_token is None:
258
+ _local_chat_tokenizer.pad_token = _local_chat_tokenizer.eos_token
259
 
260
+ base_model = AutoModelForCausalLM.from_pretrained(
261
+ LOCAL_CHAT_MODEL_ID, quantization_config=bnb_config, device_map="auto",
262
+ )
263
+ _local_chat_model = PeftModel.from_pretrained(base_model, LOCAL_LORA_ADAPTER_ID)
264
+ return _local_chat_model, _local_chat_tokenizer
 
 
 
 
 
 
265
 
266
 
267
+ @spaces.GPU
268
+ def local_chat_completion(messages, max_tokens=500):
269
+ """Run the fine-tuned model locally on the Space's GPU instead of calling
270
+ the router. Same call signature as chat_completion() so callers don't
271
+ need to know which path is active."""
272
+ import torch
273
+
274
+ model, tokenizer = get_local_chat_model()
275
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
276
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
277
+ with torch.no_grad():
278
+ output = model.generate(
279
+ **inputs, max_new_tokens=max_tokens, do_sample=True, temperature=0.7,
280
+ pad_token_id=tokenizer.pad_token_id,
281
+ )
282
+ return tokenizer.decode(output[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
283
 
284
 
285
+ def chat_completion(messages, max_tokens=500):
286
+ """Dispatches to the local fine-tuned model if configured (USE_LOCAL_CHAT_MODEL),
287
+ otherwise calls the Hugging Face Inference Providers router directly
288
+ (OpenAI-compatible). If the local model is configured but fails for any
289
+ reason, falls back to the router automatically rather than hard-failing --
290
+ same philosophy as the router's own multi-model fallback below.
291
 
292
+ Free-tier model availability on HF's router shifts over time -- providers
293
+ add/drop models from their own catalogs independently of anything in this
294
+ app. Rather than hard-failing the moment the configured model disappears,
295
+ this tries a short list of fallback candidates in order and only raises
296
+ once all of them have failed.
297
  """
298
+ if USE_LOCAL_CHAT_MODEL:
299
+ try:
300
+ return local_chat_completion(messages, max_tokens)
301
+ except Exception as e:
302
+ print(f"Local chat model failed ({e}); falling back to router.")
303
 
304
+ if GROQ_API_KEY:
305
+ for gm in GROQ_MODELS:
306
+ try:
307
+ gr_resp = requests.post(
308
+ GROQ_URL,
309
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
310
+ json={"model": gm, "messages": messages,
311
+ "max_tokens": max_tokens * 2 if "gpt-oss" in gm.lower() else max_tokens},
312
+ timeout=30,
313
+ )
314
+ if gr_resp.status_code in (401, 403):
315
+ print(f"Groq key rejected (HTTP {gr_resp.status_code}); skipping Groq.")
316
+ break
317
+ if gr_resp.ok:
318
+ gtext = (gr_resp.json()["choices"][0]["message"].get("content") or "").strip()
319
+ if gtext:
320
+ return gtext
321
+ else:
322
+ print(f"Groq model {gm} failed: HTTP {gr_resp.status_code}") # includes 429 rate limits
323
+ except Exception as e:
324
+ print(f"Groq model {gm} error: {e}")
325
 
326
+ if not HF_TOKEN:
327
+ if GROQ_API_KEY:
328
+ raise RuntimeError("All Groq models failed or are rate-limited, and no HF_TOKEN is set as a backup.")
329
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
+ candidates = [CHAT_MODEL_ID] + [m for m in CHAT_MODEL_FALLBACKS if m != CHAT_MODEL_ID]
332
+ last_error = None
 
333
 
334
+ for model_id in candidates:
335
+ resp = requests.post(
336
+ ROUTER_URL,
337
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
338
+ json={"model": model_id, "messages": messages, "max_tokens": max_tokens},
339
+ timeout=60,
340
+ )
341
+ if resp.ok:
342
+ data = resp.json()
343
+ return data["choices"][0]["message"]["content"]
344
 
345
  try:
346
+ detail = resp.json()
347
+ code = detail.get("error", {}).get("code", "")
348
  except Exception:
349
+ detail = resp.text
350
+ code = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
 
352
+ last_error = f"{resp.status_code} error for model '{model_id}': {detail}"
353
 
354
+ # Only fall through to the next candidate for availability-type errors.
355
+ # Anything else (bad payload, auth, rate limit) will fail the same way
356
+ # for every model, so surface it immediately instead of masking it.
357
+ if code not in ("model_not_supported", "model_not_found"):
358
+ raise RuntimeError(last_error)
359
 
360
+ raise RuntimeError(
361
+ f"All {len(candidates)} configured chat models are currently unavailable. Last error: {last_error}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  )
363
 
364
 
365
+ def local_fallback_response(preds=None, language="English"):
366
+ """A response that makes zero external API calls -- this is the true final
367
+ fallback, used only when every configured chat model in CHAT_MODEL_FALLBACKS
368
+ has failed. No remote model can ever be *guaranteed* available (that's the
369
+ whole reason the fallback list exists), but this can be: it only depends on
370
+ the image classifier, which runs locally on this Space's own hardware, not
371
+ on HF's shared router. If `preds` (classifier output) is available, this
372
+ still gives a real, accurate severity read -- just without the LLM's
373
+ natural-language elaboration.
374
+ """
375
+ if preds:
376
+ top = preds[0]
377
+ sev = severity_line(top["label"], language)
378
+ if language == "日本語":
379
+ return (
380
+ "⚠️ 現在、AIチャットモデルに接続できません(設定されているすべてのモデルが"
381
+ "利用できませんでした)。分類器の結果のみに基づく簡易情報です:\n\n"
382
+ f"**最も可能性の高い分類:** {top['label']}({top['score']*100:.1f}%)\n\n"
383
+ f"{sev}\n\n"
384
+ "詳しい説明は現在提供できません。しばらくしてから再度お試しいただくか、"
385
+ "重症度が「高」の場合や不安がある場合は医師にご相談ください。"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  )
387
+ return (
388
+ "⚠️ I can't reach any AI chat model right now (every configured model is "
389
+ "currently unavailable). Here's what I can still tell you from the image "
390
+ f"classifier alone:\n\n**Most likely category:** {top['label']} ({top['score']*100:.1f}%)\n\n"
391
+ f"{sev}\n\n"
392
+ "A fuller explanation isn't available right now. Please try again shortly, "
393
+ "or if the severity above is High or you're concerned, see a doctor directly."
394
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
 
396
+ if language == "日本語":
397
+ return (
398
+ "⚠️ 現在、AIチャットモデルに接続できません(設定されているすべてのモデルが"
399
+ "利用できませんでした)。しばらくしてから再度お試しください。"
400
+ "急を要する症状がある場合は、AIの応答を待たずに医師の診察を受けてください。"
401
+ )
402
+ return (
403
+ "⚠️ I can't reach any AI chat model right now (every configured model is "
404
+ "currently unavailable). Please try again in a little while. If you're dealing "
405
+ "with an urgent symptom, don't wait on this — see a doctor directly."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  )
407
 
 
 
 
408
 
409
+ def classify_image(image, language="English"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  """Run the primary classifier and return (preds, formatted_lines). If the top
411
  prediction looks like a mixed/ambiguous pigmented-lesion label and a second
412
  lesion-specific model is configured, also run that for a second opinion."""
413
  clf = get_classifier()
414
  preds = clf(image, top_k=5)
415
+ desc_dict = KNOWN_DESCRIPTIONS_JA if language == "日本語" else KNOWN_DESCRIPTIONS
416
  lines = []
417
  for p in preds:
418
  label = p["label"]
419
  score = p["score"] * 100
420
+ desc = desc_dict.get(label.lower(), "")
421
  desc_txt = f" \n _{desc}_" if desc else ""
422
  lines.append(f"- **{label}** — {score:.1f}%{desc_txt}")
423
 
 
426
  lesion_clf = get_lesion_classifier()
427
  if lesion_clf is not None:
428
  lesion_preds = lesion_clf(image, top_k=3)
429
+ second_opinion_label = (
430
+ "第二意見(このモデルではメラノーマが独立したラベルです):"
431
+ if language == "日本語"
432
+ else "Second opinion from a lesion-specific model (melanoma is a distinct label here):"
433
+ )
434
+ lines.append(f"\n_{second_opinion_label}_")
435
  for p in lesion_preds:
436
  lines.append(f"- **{p['label']}** — {p['score']*100:.1f}%")
437
  preds = preds + [{"label": f"[lesion-model] {p['label']}", "score": p["score"]} for p in lesion_preds]
 
440
 
441
 
442
  def build_classifier_context(preds):
443
+ """Turn classifier output into a compact context block for the LLM (not shown raw to the user)."""
444
  parts = []
445
  for p in preds[:4]:
446
  label = p["label"]
447
  if label.startswith("[lesion-model]"):
448
+ # second-opinion predictions: tier by the underlying label, minus the tag
449
  bare = label.replace("[lesion-model] ", "")
450
  tier = classify_tier(bare)
451
  parts.append(f"{label} ({p['score']*100:.1f}%, second-opinion, {tier})")
 
456
  return "Image classifier findings for your use (do not read these percentages verbatim): " + "; ".join(parts)
457
 
458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  # ---------------------------------------------------------------------------
460
  # Image diagnosis tab (single-shot: upload -> classify -> explain)
461
  # ---------------------------------------------------------------------------
462
  @spaces.GPU
463
+ def diagnose_image(image, language="English"):
464
  if image is None:
465
+ return "Please upload an image or pick one of the test images first。 画像をアップロードするか、テスト画像を選択してください。"
466
 
467
  try:
468
+ preds, lines_list = classify_image(image, language)
469
  except Exception as e:
470
  return f"**Model error:** {e}\n\nMake sure `IMAGE_MODEL_ID` is a valid image-classification model."
471
 
472
+ header = "### 🔬 分類結果\n" if language == "日本語" else "### 🔬 Classifier prediction\n"
473
+ lines = [header] + lines_list
474
+ lines.append(f"\n{severity_line(preds[0]['label'], language)}")
475
+
476
+ if CHAT_ENABLED:
477
+ context = build_classifier_context(preds)
478
+ lang_instruction = (
479
+ "Respond entirely in natural, fluent Japanese (日本語)."
480
+ if language == "日本語"
481
+ else "Respond entirely in English."
482
+ )
483
+ prompt = (
484
+ f"{context}\n\n"
485
+ "The user just uploaded a single image with no conversation yet. Give a short "
486
+ "preliminary assessment following your instructions: plain-language explanation of "
487
+ "the top finding(s), an explicit Low/Medium/High severity call, and a brief natural "
488
+ "mention that an in-person exam is what actually confirms things. Note that without "
489
+ "any conversation history you have less context than usual — you can still give your "
490
+ "best read, but you may want to suggest the Chat Assistant for a fuller picture if the "
491
+ f"case seems ambiguous. Keep it to 5-7 sentences. {lang_instruction}"
492
  )
493
+ try:
494
+ explanation = chat_completion(
495
+ [
496
+ {"role": "system", "content": SYSTEM_PROMPT},
497
+ {"role": "user", "content": prompt},
498
+ ],
499
+ max_tokens=350,
500
+ )
501
+ header = "🤖 Assessment" if language == "English" else "🤖 診断アシスタントの見解"
502
+ lines.append(f"\n### {header}\n{explanation}")
503
+ except Exception as e:
504
+ fallback_header = "🤖 Assessment (offline mode)" if language == "English" else "🤖 診断アシスタントの見解(オフラインモード)"
505
+ lines.append(f"\n### {fallback_header}\n{local_fallback_response(preds, language)}")
506
+ lines.append(f"\n<sub>_Debug detail: {e}_</sub>")
507
+ else:
508
  lines.append(
509
+ "\n_Add a `GROQ_API_KEY` or `HF_TOKEN` secret to this Space to also get a plain-language "
510
+ "assessment from the chat model here._"
511
  )
 
 
512
 
513
  lines.append(
514
  "\n---\n_Tip: use the **Chat Assistant** tab for a fuller triage conversation — "
515
+ "it can ask follow-up questions and give a more tailored read. "
516
+ "(より詳しい問診は「Chat Assistant」タブをご利用ください)_"
517
  )
518
  return "\n".join(lines)
519
 
 
521
  # ---------------------------------------------------------------------------
522
  # Chat tab — multimodal, multi-turn triage
523
  # ---------------------------------------------------------------------------
524
+ MIN_ROUNDS_BEFORE_ASSESSMENT = 4 # user turns, not counting the current one
525
+
526
+
527
  def _extract_text_and_image(message):
528
+ """Normalize gr.ChatInterface(multimodal=True) message input into (text, image_path_or_None)."""
529
  if isinstance(message, dict):
530
  text = message.get("text", "") or ""
531
  files = message.get("files") or []
532
+ image_path = files[0] if files else None
 
533
  return text, image_path
534
  return str(message), None
535
 
 
539
 
540
 
541
  def _stage_note(user_turn_count):
542
+ """Injected each turn so multi-round behavior is enforced by code, not just
543
+ requested once in the system prompt — the model gets a fresh reminder of
544
+ what stage the conversation is in on every single call."""
545
  if user_turn_count < MIN_ROUNDS_BEFORE_ASSESSMENT:
546
  return (
547
  f"[Internal note — not from the user: this is exchange {user_turn_count} of at least "
 
559
  )
560
 
561
 
562
+ def _detect_language(text):
563
+ """Cheap heuristic for the local fallback only -- checks for Hiragana/Katakana/
564
+ common Kanji characters. The main chat flow doesn't need this (the LLM itself
565
+ handles language-mirroring), but the local fallback has no LLM to ask."""
566
+ if not text:
567
+ return "English"
568
+ for ch in text:
569
+ code = ord(ch)
570
+ if (0x3040 <= code <= 0x30FF) or (0x4E00 <= code <= 0x9FFF):
571
+ return "日本語"
572
+ return "English"
573
+
574
+
575
+ def chat_respond(message, history):
576
+ if not CHAT_ENABLED:
577
+ return (
578
+ "Chat isn't configured yet — add a `GROQ_API_KEY` or `HF_TOKEN` secret to this Space "
579
+ "(Settings → Variables and secrets) to enable the chatbot."
580
+ )
581
 
582
+ text, image_path = _extract_text_and_image(message)
583
+ preds = None # hoisted so it's available to the local fallback below, if an image was shared
584
 
585
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
586
+ for turn in history:
 
 
587
  if isinstance(turn, dict):
588
+ role = turn.get("role")
589
+ content = turn.get("content")
590
+ if isinstance(content, str):
591
+ messages.append({"role": role, "content": content})
 
592
  else:
593
+ user_msg, bot_msg = turn
594
+ if isinstance(user_msg, str):
595
+ messages.append({"role": "user", "content": user_msg})
596
+ if bot_msg:
597
+ messages.append({"role": "assistant", "content": bot_msg})
 
 
 
 
 
 
 
 
 
 
598
 
599
+ user_content = text
 
600
  if image_path:
601
  try:
602
+ img = Image.open(image_path)
603
+ preds, _ = classify_image(img)
604
+ context = build_classifier_context(preds)
605
+ user_content = f"{context}\n\nUser's message: {text or '(no message, just shared an image)'}"
606
  except Exception as e:
607
+ user_content = f"(Image analysis failed: {e})\n\nUser's message: {text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
608
 
609
+ # current turn counts too, since the model is about to respond to it
610
  current_turn_count = _count_user_turns(messages) + 1
611
+ stage_note = _stage_note(current_turn_count)
612
+ messages.append({"role": "user", "content": f"{stage_note}\n\n{user_content}"})
613
 
614
  try:
615
+ return chat_completion(messages, max_tokens=500)
616
+ except Exception as e:
617
+ detected_lang = _detect_language(text)
618
+ fallback = local_fallback_response(preds, detected_lang)
619
+ note = (
620
+ f"\n\n<sub>_Debug detail: {e}_</sub>" if detected_lang == "English"
621
+ else f"\n\n<sub>_詳細: {e}_</sub>"
622
+ )
623
+ return fallback + note
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
 
625
 
626
  # ---------------------------------------------------------------------------
 
630
 
631
 
632
  def load_performance_reports():
633
+ """Scan assets/ for model performance data in two modes:
634
+ 1. Full reports: a *_metrics.json paired with its confusion-matrix image
635
+ and any other same-prefix analysis images (threshold curves, cluster
636
+ breakdowns, etc.).
637
+ 2. Image-only reports: any *_confusion_matrix.{png,jpg,jpeg} that doesn't
638
+ have a matching metrics.json yet -- shown with its charts but no
639
+ numeric table, so you don't have to wait on exporting metrics.json
640
+ just to see the images you already generated.
641
+ Returns a list of dicts; empty list if nothing's been uploaded at all.
642
+ """
643
  import json
644
 
645
  reports = []
646
  if not os.path.isdir(ASSETS_DIR):
647
  return reports
648
  all_files = sorted(os.listdir(ASSETS_DIR))
649
+ claimed = set() # filenames already used by a full (metrics.json-backed) report
650
 
651
+ # --- Pass 1: full reports (metrics.json + its images) ---
652
  for fname in all_files:
653
  if not fname.endswith("_metrics.json"):
654
  continue
 
679
 
680
  reports.append({"data": data, "image_path": image_path, "extra_images": extra_images})
681
 
682
+ # --- Pass 2: image-only reports -- any confusion-matrix image not already
683
+ # claimed by a full report above, grouped with its same-prefix siblings ---
684
  seen_prefixes = set()
685
  for fname in all_files:
686
  if fname in claimed or not fname.lower().endswith((".png", ".jpg", ".jpeg")):
687
  continue
688
+ marker = "_confusion_matrix"
689
+ idx = fname.lower().find(marker)
690
  if idx == -1:
691
+ continue # only auto-surface files that look like a confusion matrix
692
  prefix = fname[:idx]
693
  if prefix in seen_prefixes:
694
  continue
 
704
  extra_images.append({"path": os.path.join(ASSETS_DIR, other), "label": label})
705
  claimed.add(other)
706
 
707
+ model_name = prefix.replace("_", " ").strip().title() or "Model"
708
  reports.append({
709
+ "data": {"model_name": model_name, "image_only": True},
710
  "image_path": os.path.join(ASSETS_DIR, fname),
711
  "extra_images": extra_images,
712
  })
 
721
  if data.get("image_only"):
722
  lines.append(
723
  "_Charts available — metrics summary not uploaded yet. Add a matching "
724
+ "`*_metrics.json` to this prefix for the full accuracy/F1/per-class table. "
725
+ "/ 数値指標は未アップロードです。同じ接頭辞の `*_metrics.json` を追加すると、"
726
+ "精度・F1・クラス別表が表示されます。_"
727
  )
728
  return "\n".join(lines)
729
 
 
751
 
752
  ABOUT_MARKDOWN = f"""
753
  ## About this project
754
+
755
  A research/portfolio demo exploring how far an image classifier + LLM chat
756
  assistant can go toward useful skin-condition triage — while being explicit
757
  about what it isn't: a validated medical device.
758
+
759
  ### What's inside
760
  - **Quick Image Check** — upload a photo, get a classifier prediction plus
761
  an LLM-generated plain-language assessment with an explicit Low/Medium/High
 
764
  evolution, symptoms, triggers, and history before giving a more targeted
765
  preliminary read than a single photo alone could support.
766
  - **Model Performance** — the actual test-set metrics for whichever
767
+ fine-tuned model(s) are currently backing this app, not just marketing
768
+ claims about accuracy.
769
+
770
  ### Models
771
+ - **Image classifier:** configurable via the `IMAGE_MODEL_ID` variable.
772
+ Two purpose-built options are included as fine-tuning notebooks in this
773
+ repo: a 7-class pigmented-lesion model (HAM10000/ISIC, ViT-Base) and a
774
+ 23-class common-skin-condition model (DermNet, ConvNeXt-Base).
775
+ - **Optional second-opinion lesion model:** `LESION_MODEL_ID`, used
776
+ automatically when the primary model's top prediction is an ambiguous
777
+ mixed melanoma/mole-type label, to get a model that treats melanoma as
778
+ its own distinct class.
779
+ - **Chat model:** configurable via `CHAT_MODEL_ID`, served through Hugging
780
+ Face's Inference Providers router.
781
+
 
782
  ### Severity levels
783
  - 🔴 **High** — cancer-related, ambiguous-but-could-be-serious, systemic/
784
  autoimmune, or red-flag symptoms present. See a doctor soon.
 
786
  (infections, infestations). See a doctor, not an emergency.
787
  - 🟢 **Low** — typically manageable with general skin care. Doctor visit
788
  optional, especially if unsure or it's not improving.
789
+
790
+ ### Known limitations (read this before trusting the output)
791
  - **Not clinically validated.** Benchmark accuracy on a public dataset is
792
  not the same as real-world diagnostic reliability.
793
+ - **Dataset label limitations.** The DermNet taxonomy combines melanoma
794
+ with benign moles under one label — the app defaults that whole category
795
+ to High severity rather than pretending to distinguish them.
796
  - **Skin-tone representation.** Public dermatology datasets skew toward
797
+ lighter skin tones; performance on underrepresented skin tones is
798
+ unverified without a dedicated bias audit.
799
  - **No clinical validation, IRB review, or regulatory clearance** has been
800
  done. This should inform, not replace, professional care.
801
+
802
  {PAGE_DISCLAIMER}
803
+
804
+ ---
805
+
806
+ ## このプロジェクトについて(日本語)
807
+
808
+ 画像分類AIとLLMチャットアシスタントを組み合わせ、皮膚の状態に関する
809
+ トリアージ(受診要否の判断支援)をどこまで実現できるかを探る、
810
+ 研究・ポートフォリオ用のデモです。**医療機器ではありません。**
811
+
812
+ ### 主な機能
813
+ - **画像チェック** — 写真をアップロードすると、分類結果と
814
+ Low/Medium/High の重症度、そしてLLMによる平易な解説を表示します。
815
+ - **チャットアシスタント** — 発症時期・経過・症状・きっかけ・既往歴などを
816
+ 尋ねながら、写真単体よりも踏み込んだ見解を提示します。日本語・英語の
817
+ 両方に対応しています。
818
+ - **モデル性能** — 実際のテストデータに基づく評価指標を公開しています。
819
+
820
+ ### 重症度レベル
821
+ - 🔴 **高(High)** — がん関連の疑い、または良性と判別できない曖昧な
822
+ 所見、自己免疫・全身性の兆候、危険信号がある場合。早めの受診を
823
+ 推奨します。
824
+ - 🟡 **中(Medium)** — 感染症など、正式な診断・処方が必要な状態。
825
+ 緊急ではありませんが受診をおすすめします。
826
+ - 🟢 **低(Low)** — 一般的なスキンケアで対応できることが多い状態。
827
+ 不安な場合や改善しない場合は受診も選択肢です。
828
+
829
+ ### 既知の限界(必ずお読みください)
830
+ - **臨床的な検証は行われていません。** 公開データセットでの精度は、
831
+ 実世界での診断的信頼性を意味しません。
832
+ - **データセットのラベルに関する限界。** 一部のタクソノミーでは
833
+ メラノーマと良性のほくろが同一ラベルに含まれる��合があり、
834
+ その場合は安全側に倒して重症度を「高」としています。
835
+ - **肌タイプの偏り。** 公開されている皮膚科データセットは色白の肌タイプに
836
+ 偏っている傾向があり、その他の肌タイプでの性能は未検証です。
837
+ - 本ツールはあくまで参考情報であり、専門的な医療の代わりにはなりません。
838
  """
839
 
840
 
 
850
  if f.lower().endswith((".jpg", ".jpeg", ".png"))
851
  ]
852
 
853
+ with gr.Blocks(title="Skin Disease Detection — Demo / 皮膚疾患検出デモ") as demo:
854
+ gr.Markdown("# 🩺 Skin Disease Detection / 皮膚疾患検出AI")
855
+ gr.Markdown(f"_{PAGE_DISCLAIMER}_\n\n_本ツールは研究・ポートフォリオ用のプロジェクトであり、医療機器ではありません。臨床的な検証は行われていません。実際の受診の代わりではなく、参考情報としてご利用ください。_")
 
 
 
 
 
 
 
 
 
 
856
 
857
  with gr.Tab("📷 Quick Image Check"):
858
  with gr.Row():
859
  with gr.Column():
860
+ img_in = gr.Image(type="pil", label="Upload a skin image / 画像をアップロード")
861
+ lang_select = gr.Radio(
862
+ choices=["English", "日本語"], value="English",
863
+ label="Assessment language / 診断結果の言語",
864
+ )
865
  if example_images:
866
+ gr.Examples(examples=example_images, inputs=img_in, label="Or try a test image / テスト画像を試す")
867
  else:
868
  gr.Markdown(
869
  "_No bundled test images found. Run `scripts/download_examples.py` "
870
  "before deploying, or just upload your own image._"
871
  )
872
+ analyze_btn = gr.Button("Analyze image / 画像を解析", variant="primary")
873
  with gr.Column():
874
  result_md = gr.Markdown()
875
+ analyze_btn.click(diagnose_image, inputs=[img_in, lang_select], outputs=result_md)
876
 
877
+ with gr.Tab("💬 Chat Assistant / チャット"):
878
  gr.ChatInterface(
879
  fn=chat_respond,
880
  multimodal=True,
 
881
  description=(
882
  "Talk through what you're noticing, and optionally attach a photo (📎). "
883
  "The assistant will ask several follow-up questions before giving a preliminary "
884
  "read with a Low/Medium/High severity call — the more you share, the more "
885
+ "targeted that read can be. You can write in English or Japanese (日本語) — "
886
+ "the assistant will respond in the same language. "
887
+ "気になる症状について自由にお話しください。写真の添付も可能です(📎)。"
888
+ "いくつか質問をした上で、重症度(Low/Medium/High)を含む見解をお伝えします。"
889
+ "日本語でも英語でもご利用いただけます。"
890
  ),
891
  )
892
 
893
+ with gr.Tab("📊 Model Performance / 性能"):
894
  performance_reports = load_performance_reports()
895
  if not performance_reports:
896
  gr.Markdown(
 
898
  "Run either fine-tuning notebook in this repo, then download the "
899
  "`*_metrics.json` and `*_confusion_matrix.png` files it produces and place "
900
  "them in this Space's `assets/` folder. This tab picks them up automatically "
901
+ "on the next restart.\n\n"
902
+ "_モデル性能データはまだありません。_ 付属のノートブックを実行し、出力される "
903
+ "`*_metrics.json` と `*_confusion_matrix.png` をこのSpaceの `assets/` フォルダに配置してください。"
904
+ "次回の���起動時に自動的に反映されます。"
905
  )
906
  else:
907
  for report in performance_reports:
908
  gr.Markdown(format_performance_markdown(report))
909
  if report["image_path"]:
910
+ gr.Image(value=report["image_path"], label="Confusion matrix (test set) / 混同行列", show_label=True)
911
  for extra in report.get("extra_images", []):
912
+ gr.Image(value=extra["path"], label=f"{extra['label']} / 追加分析", show_label=True)
913
 
914
+ with gr.Tab("ℹ️ About / 概要"):
915
  gr.Markdown(ABOUT_MARKDOWN)
916
 
917
  gr.Markdown(
918
  "---\nBuilt with 🤗 Transformers + Gradio. "
919
+ f"Image model: `{IMAGE_MODEL_ID}` · Chat model: `{CHAT_MODEL_ID}` · "
920
+ "Supports English and Japanese (日本語対応)"
921
  )
922
 
923
  if __name__ == "__main__":
924
+ demo.launch()