retinaplus Claude Opus 4.8 commited on
Commit
3e481a4
·
1 Parent(s): 538b9e8

Integrate full screening pipeline: quality gate + calibration + lesion explain

Browse files

- quality gate (heuristic + EyeQ, fundus/mobile profiles for 20D)
- grade-anchored 3-zone screening (calibrated) + binary verdict UI
- lazy lesion explain (/explain): UNet MA/HE/EX/SE + disc/fovea/ETDRS + DD distance
- EX/SE brightness filter (fix fovea false-positive)
- responsive screener-first layout + collapsible clinical deep-dive
- update README, requirements (smp/sklearn/joblib), drop grad-cam

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ _demo.png
4
+ _t*.png
README.md CHANGED
@@ -6,38 +6,61 @@ colorTo: indigo
6
  sdk: docker
7
  app_port: 8080
8
  pinned: false
9
- short_description: AI diabetic retinopathy screening
10
  ---
11
 
12
  # RetinaPlus — AI Diabetic Retinopathy Screening
13
 
14
- เครื่องมือคัดกรองเบาหวานขึ้นจอตาด้วย AI · Flask + PyTorch (EfficientNet-B4 ordinal regression, ensemble v3+v4 + TTA) + Grad-CAM
15
 
16
- > ⚠️ เครื่องมือคัดกรองเบื้องต้น ไม่ใช่การวินิจฉัย ผลควรได้รับการยืนยันโดยจักษุแพทย์
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  ## หน้าเว็บ
19
- - `/` หน้าแรก · `/detect` ถ่าย/อัปโหลดภาพจอตา → ผลตรวจ · `/dashboard` สรุปผล
20
 
21
- ## โมเดล
22
- EfficientNet-B4 ensemble (2 seeds) — `models/v3_best.pt`, `models/v4_best.pt`
23
- ถ้าโฟลเดอร์ว่าง → รันได้แต่เป็น "โหมดสาธิต"
24
 
25
  ## รัน Local
26
  ```bash
27
- pip install torch --index-url https://download.pytorch.org/whl/cpu
28
  pip install -r requirements.txt
29
  python app.py # http://localhost:8080
30
  ```
31
 
32
  ## Deploy
33
- - **Hugging Face Spaces (Docker):** push repo นี้ → HF build จาก Dockerfile อัตโนมัติ (`app_port: 8080`)
34
- - **Google Cloud Run:** `gcloud run deploy retinaplus --source . --memory 2Gi --cpu 2 --allow-unauthenticated`
35
 
36
  ## API
37
  | route | |
38
  |---|---|
39
- | `GET /status` | สถานะโมเดล |
40
- | `POST /predict` | form-data `image` → JSON: grade, score, referable, risk_percent, gradcam(base64) |
 
41
  | `GET /history` · `GET /stats` | ประวัติ + สรุป |
42
 
 
 
 
 
43
  Developed by Nathakorn
 
6
  sdk: docker
7
  app_port: 8080
8
  pinned: false
9
+ short_description: AI diabetic retinopathy screening + lesion explanation
10
  ---
11
 
12
  # RetinaPlus — AI Diabetic Retinopathy Screening
13
 
14
+ เครื่องมือ **คัดกรองเบาหวานขึ้นจอประสาทตา (DR)** จากภาพ fundus ด้วย AI พร้อม **คำอธิบายรอยโรคช่วยแพทย์** · Flask + PyTorch
15
 
16
+ > ⚠️ เครื่องมือ **ช่วยตัดสินใจ (decision-support)** ไม่ใช่การวินิจฉัยขั้นสุดท้าย — ผลต้องได้รับการยืนยันโดยจักษุแพทย์
17
+
18
+ ## Pipeline
19
+ ```
20
+ ภาพ → [1] Quality gate (heuristic + EyeQ, 2 โหมด: กล้องมาตรฐาน / มือถือ+20D)
21
+ → [2] คัดกรอง: ensemble v3+v4 (EfficientNet-B4 ordinal) + TTA → calibrated risk
22
+ → [3] โซน: 🟢 ไม่ต้องส่งต่อ / 🔴 ควรพบจักษุแพทย์ (grade-anchored)
23
+ → [4] อธิบายรอยโรค (lazy): UNet++ segment MA/HE/EX/SE + disc/fovea/ETDRS + ระยะ DD
24
+ ```
25
+
26
+ - **คัดกรองเร็ว** (`/predict` ~3s) แยกจาก **อธิบายรอยโรค** (`/explain`) ที่โหลดเฉพาะตอนเปิด "ข้อมูลเชิงลึก"
27
+ - หน้าจอ 2 ชั้น: คนคัดกรองเห็นผล พบ/ไม่พบแพทย์ + ความเสี่ยง · แพทย์กดดู overlay รอยโรค + รายงานเชิงตัวเลข
28
+
29
+ ## ผลการประเมิน (external validation)
30
+ | ชุด | QWK | Referable AUC | sens / spec |
31
+ |---|---|---|---|
32
+ | internal test | 0.88 | 0.94 | 0.83 / 0.94 |
33
+ | external IDRiD | 0.85 | 0.98 | 0.93 / 0.91 |
34
+ | external DDR (n=12,522) | 0.80 | 0.95 | — |
35
 
36
  ## หน้าเว็บ
37
+ - `/` หน้าแรก · `/detect` ตรวจ (ถ่าย/อัปโหลด) · `/dashboard` สรุปสถิติ
38
 
39
+ ## โมเดล (`models/`)
40
+ `v3_best.pt` + `v4_best.pt` (classifier ensemble) · `unet_lesion_v2.pt` (lesion) · `quality_gate.pt` (EyeQ B0)
41
+ config (`config/`): `calibrator.pkl`, `thresholds.json`, `quality_gate_config.json`
42
 
43
  ## รัน Local
44
  ```bash
45
+ pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cpu
46
  pip install -r requirements.txt
47
  python app.py # http://localhost:8080
48
  ```
49
 
50
  ## Deploy
51
+ - **Hugging Face Spaces (Docker):** push repo → build จาก Dockerfile อัตโนมัติ (`app_port: 8080`)
52
+ - **Cloud Run:** `gcloud run deploy retinaplus --source . --memory 2Gi --cpu 2 --allow-unauthenticated`
53
 
54
  ## API
55
  | route | |
56
  |---|---|
57
+ | `GET /status` | สถานะโมเดล + โปรไฟล์ quality gate |
58
+ | `POST /predict` | form-data `image`, `mode` → JSON: grade, risk_percent, zone, layers.raw |
59
+ | `POST /explain` | form-data `image` → lesion layers + features + rationale + disc/fovea (lazy) |
60
  | `GET /history` · `GET /stats` | ประวัติ + สรุป |
61
 
62
+ ## ข้อจำกัด / งานในอนาคต
63
+ - โมเดลเทรนบน **กล้อง fundus ตั้งโต๊ะ** — ภาพ **มือถือ+เลนส์ 20D** เป็น domain shift ต้องเก็บภาพจริง + fine-tune + recalibrate ก่อนใช้คลินิก
64
+ - จุดอ่อน: Moderate precision, EyeQ gate เข้มกับบางโดเมน → แก้ด้วย fine-tune (NB5) + ONNX/int8 (NB4) ในอนาคต
65
+
66
  Developed by Nathakorn
__pycache__/app.cpython-310.pyc DELETED
Binary file (9.89 kB)
 
app.py CHANGED
@@ -1,7 +1,12 @@
1
  """
2
  RetinaPlus — AI Diabetic Retinopathy Screening (web)
3
- Flask + PyTorch (EfficientNet-B4 ordinal regression) + Grad-CAM
4
- โครงเดียวกับ Cough AI: เสิร์ฟ static html + /predict API + Cloud Run ready
 
 
 
 
 
5
  """
6
  import os, io, json, base64, datetime, traceback
7
  from pathlib import Path
@@ -12,84 +17,166 @@ from flask import Flask, request, jsonify, send_from_directory
12
  from flask_cors import CORS
13
 
14
  import torch
15
- import torch.nn as nn
16
  import timm
17
 
18
- # ------------------------------------------------------------------ config
19
  HERE = Path(__file__).resolve().parent
20
  MODELS_DIR = HERE / "models"
 
21
  HISTORY_FILE = Path(os.environ.get("HISTORY_FILE") or (HERE / "history.json"))
 
 
22
  IMG_SIZE = 380
23
  BACKBONE = "efficientnet_b4"
24
  CLASS_NAMES = ["No DR", "Mild", "Moderate", "Severe", "Proliferative"]
25
- # OptimizedRounder coefs จาก v4 (เส้นแบ่งเกรด) + referable = coef[1]
26
- ROUNDER_COEFS = [0.515, 1.264, 2.376, 3.079]
27
- REFERABLE_THR = ROUNDER_COEFS[1]
28
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # ------------------------------------------------------------------ model
31
- def build_model():
32
- m = timm.create_model(BACKBONE, pretrained=False, num_classes=1,
33
- drop_rate=0.3, drop_path_rate=0.2)
34
- return m.to(DEVICE).eval()
35
 
36
- MEMBERS = []
37
  def load_models():
38
- """โหลด best*.pt ทุกตัวใน models/ มาเป็น ensemble (ถ้าไม่มี = โหมด demo)"""
39
- global MEMBERS
40
  MEMBERS = []
41
- if MODELS_DIR.exists():
42
- for p in sorted(MODELS_DIR.glob("*.pt")):
43
- try:
44
- m = build_model()
45
- m.load_state_dict(torch.load(str(p), map_location=DEVICE))
46
- MEMBERS.append(m)
47
- print(f"[model] loaded {p.name}")
48
- except Exception as e:
49
- print(f"[model] skip {p.name}: {e}")
50
- print(f"[model] {len(MEMBERS)} model(s) | device={DEVICE}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  load_models()
52
 
53
  # ------------------------------------------------------------------ preprocessing
54
- _MEAN = np.array([0.485, 0.456, 0.406]); _STD = np.array([0.229, 0.224, 0.225])
55
-
56
- def _crop_fundus(img, tol=7):
57
- g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY); mask = g > tol
58
- if mask.sum() == 0: return img
59
- c = np.argwhere(mask); y0, x0 = c.min(0); y1, x1 = c.max(0) + 1
60
- return img[y0:y1, x0:x1]
61
 
62
- def _clahe(img):
63
- lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB); l, a, b = cv2.split(lab)
64
  l = cv2.createCLAHE(2.0, (8, 8)).apply(l)
65
  return cv2.cvtColor(cv2.merge((l, a, b)), cv2.COLOR_LAB2BGR)
66
 
67
- def preprocess(bgr):
68
- img = _crop_fundus(bgr)
69
  if img.size == 0: img = bgr
70
- img = cv2.resize(img, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_AREA)
71
- img = _clahe(img)
72
- return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # RGB uint8
73
 
74
  def to_tensor(rgb):
75
  x = ((rgb / 255.0 - _MEAN) / _STD).transpose(2, 0, 1).astype(np.float32)
76
  return torch.from_numpy(x).unsqueeze(0).to(DEVICE)
77
 
78
- def grade_from_score(s):
79
- return int(np.clip(np.digitize([s], ROUNDER_COEFS)[0], 0, 4))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- def is_fundus(bgr):
82
- """heuristic: ภาพจอตา = โทนแดง/ส้ม + มีบริเวณสว่างเป็นก้อนใหญ่"""
83
- img = cv2.resize(bgr, (256, 256))
84
- rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(float)
85
- redness = float(rgb[:, :, 0].mean() - rgb[:, :, 2].mean()) # R - B
86
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
87
- _, th = cv2.threshold(gray, 18, 255, cv2.THRESH_BINARY)
88
- cnts, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
89
- fill = (max(cv2.contourArea(c) for c in cnts) / (256 * 256)) if cnts else 0.0
90
- return (redness > 18) and (fill > 0.15)
91
-
92
- # ------------------------------------------------------------------ inference + grad-cam
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  @torch.no_grad()
94
  def ensemble_score(x):
95
  ss = []
@@ -99,46 +186,172 @@ def ensemble_score(x):
99
  ss.append(float((o / 3).item()))
100
  return float(np.mean(ss))
101
 
102
- def gradcam_overlay(rgb, x):
103
- """heatmap จากโมเดลตัวแรก + mask วงจอตา -> base64 png"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  try:
105
- from pytorch_grad_cam import GradCAMPlusPlus
106
- from pytorch_grad_cam.utils.image import show_cam_on_image
107
- m0 = MEMBERS[0]
108
- tl = m0.blocks[-2] if (hasattr(m0, "blocks") and len(m0.blocks) >= 2) else m0.conv_head
109
- cam = GradCAMPlusPlus(model=m0, target_layers=[tl])
110
- class T:
111
- def __call__(self, o): return o[0]
112
- gray = cam(input_tensor=x, targets=[T()])[0]
113
- g = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
114
- mask = cv2.erode((g > 15).astype(np.float32), np.ones((25, 25), np.uint8))
115
- gray = gray * mask
116
- if gray.max() > 1e-6: gray = gray / gray.max()
117
- ov = show_cam_on_image(rgb.astype(np.float32) / 255.0, gray, use_rgb=True)
118
- ok, buf = cv2.imencode(".png", cv2.cvtColor(ov, cv2.COLOR_RGB2BGR))
119
- return base64.b64encode(buf).decode() if ok else None
120
- except Exception as e:
121
- print("[gradcam] skip:", e); return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- def b64_png(rgb):
124
- ok, buf = cv2.imencode(".png", cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  return base64.b64encode(buf).decode() if ok else None
126
 
127
- # ------------------------------------------------------------------ history
128
- def save_history(rec):
129
- try:
130
- data = load_history()
131
- data.insert(0, rec); data = data[:200]
132
- HISTORY_FILE.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
133
- except Exception:
134
- pass # read-only filesystem (e.g. HF Spaces) — skip persistence silently
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
 
136
  def load_history(limit=200):
137
  if HISTORY_FILE.exists():
138
  try: return json.loads(HISTORY_FILE.read_text(encoding="utf-8"))[:limit]
139
  except Exception: return []
140
  return []
141
 
 
 
 
 
 
 
142
  # ------------------------------------------------------------------ flask
143
  app = Flask(__name__, static_folder=".", static_url_path="")
144
  CORS(app)
@@ -152,71 +365,82 @@ def dash(): return send_from_directory(".", "dashboard.html")
152
 
153
  @app.route("/<path:f>")
154
  def assets(f):
155
- if (HERE / f).is_file(): return send_from_directory(".", f)
156
- return ("", 404)
157
 
158
  @app.route("/status")
159
  def status():
160
- return jsonify({"ok": True, "models": len(MEMBERS), "device": DEVICE,
161
- "demo": len(MEMBERS) == 0})
 
 
 
 
 
162
 
163
  @app.route("/predict", methods=["POST"])
164
  def predict():
165
  try:
166
- if "image" not in request.files:
167
- return jsonify({"error": "no image"}), 400
168
  raw = np.frombuffer(request.files["image"].read(), np.uint8)
169
  bgr = cv2.imdecode(raw, cv2.IMREAD_COLOR)
170
  if bgr is None: return jsonify({"error": "bad image"}), 400
 
171
 
172
- if not is_fundus(bgr):
173
- return jsonify({"not_fundus": True,
174
- "message_th": "ภาพนี้ไม่ใช่ภาพจอประสาทตา — กรุณาถ่าย/อัปโหลดภาพถ่ายจอตา (fundus)",
175
- "message_en": "This is not a retinal fundus image — please capture/upload a fundus photo."})
176
-
177
- rgb = preprocess(bgr)
178
 
179
- if len(MEMBERS) == 0: # demo mode (ไม่มีโมเดล)
180
- score = 1.9
181
- res = {"demo": True}
182
  else:
183
- x = to_tensor(rgb)
184
- score = ensemble_score(x)
185
- res = {"demo": False}
186
-
187
- grade = grade_from_score(score)
188
- referable = score >= REFERABLE_THR
189
- # map score 0-4 -> referable risk % (sigmoid รอบ threshold)
190
- risk = float(1 / (1 + np.exp(-(score - REFERABLE_THR) * 2.2)) * 100)
191
- cam = gradcam_overlay(rgb, x) if len(MEMBERS) else None
192
-
193
- res.update({
194
- "grade": grade, "grade_name": CLASS_NAMES[grade],
195
- "score": round(score, 2),
196
- "referable": bool(referable),
197
- "risk_percent": round(risk, 1),
198
- "preprocessed": b64_png(rgb),
199
- "gradcam": cam,
200
- })
201
  save_history({"time": datetime.datetime.now().isoformat(timespec="seconds"),
202
- "grade": grade, "grade_name": CLASS_NAMES[grade],
203
- "referable": bool(referable), "risk_percent": round(risk, 1)})
204
  return jsonify(res)
205
  except Exception as e:
206
- traceback.print_exc()
207
- return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
  @app.route("/history")
210
  def history(): return jsonify(load_history())
211
 
212
  @app.route("/stats")
213
  def stats():
214
- h = load_history()
215
- n = len(h); ref = sum(1 for x in h if x.get("referable"))
216
  dist = {c: 0 for c in CLASS_NAMES}
217
  for x in h: dist[x.get("grade_name", "No DR")] = dist.get(x.get("grade_name", "No DR"), 0) + 1
218
- return jsonify({"total": n, "referable": ref, "normal": n - ref, "dist": dist})
 
 
 
219
 
220
  if __name__ == "__main__":
221
- port = int(os.environ.get("PORT", 8080))
222
- app.run(host="0.0.0.0", port=port, debug=True)
 
1
  """
2
  RetinaPlus — AI Diabetic Retinopathy Screening (web)
3
+ Flask + PyTorch. Pipeline:
4
+ quality gate (heuristic + EyeQ, mobile/20D aware)
5
+ -> ensemble v3+v4 (EfficientNet-B4 ordinal) + TTA
6
+ -> isotonic calibration -> 3 zones (normal / review / refer)
7
+ -> UNet++ lesion segmentation -> rationale + disc/fovea/ETDRS + DD distance
8
+ Returns layered overlays (raw base + lesion layer + landmark layer) for toggling.
9
+ Runs local (python app.py) and server (gunicorn) — HF Spaces / Cloud Run ready.
10
  """
11
  import os, io, json, base64, datetime, traceback
12
  from pathlib import Path
 
17
  from flask_cors import CORS
18
 
19
  import torch
 
20
  import timm
21
 
22
+ # ------------------------------------------------------------------ paths / config
23
  HERE = Path(__file__).resolve().parent
24
  MODELS_DIR = HERE / "models"
25
+ CONFIG_DIR = HERE / "config"
26
  HISTORY_FILE = Path(os.environ.get("HISTORY_FILE") or (HERE / "history.json"))
27
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
28
+
29
  IMG_SIZE = 380
30
  BACKBONE = "efficientnet_b4"
31
  CLASS_NAMES = ["No DR", "Mild", "Moderate", "Severe", "Proliferative"]
32
+ LESIONS = ["MA", "HE", "EX", "SE"]
33
+ PALETTE = {"MA": (255, 0, 0), "HE": (0, 0, 255), "EX": (0, 255, 0), "SE": (255, 255, 0)}
34
+ LES_NAME = {"MA": "microaneurysm", "HE": "hemorrhage", "EX": "hard exudate", "SE": "soft exudate/cotton-wool"}
35
+ WORK = int(os.environ.get("LESION_WORK", 1024)) # UNet sliding-window resolution (เล็กลง=เร็วขึ้นบน CPU)
36
+ PATCH = 768
37
+ MIN_AREA = 4
38
+ _MEAN = np.array([0.485, 0.456, 0.406]); _STD = np.array([0.229, 0.224, 0.225])
39
+
40
+ def _load_json(name, default):
41
+ p = CONFIG_DIR / name
42
+ if p.exists():
43
+ try: return json.loads(p.read_text(encoding="utf-8"))
44
+ except Exception: pass
45
+ return default
46
+
47
+ THRESH = _load_json("thresholds.json", {"rounder_coefs": [0.515, 1.264, 2.376, 3.079],
48
+ "P_LO": 0.03, "P_HI": 0.33})
49
+ ROUNDER_COEFS = THRESH.get("rounder_coefs", [0.515, 1.264, 2.376, 3.079])
50
+ P_LO = float(THRESH.get("P_LO", 0.03)); P_HI = float(THRESH.get("P_HI", 0.33))
51
+ QCFG = _load_json("quality_gate_config.json", {
52
+ "QIMG": 384, "classes": ["Good", "Usable", "Reject"], "default_profile": "fundus",
53
+ "profiles": {"fundus": {"AREA_MIN": 0.3, "BLUR_MIN": 15, "BRI_LO": 40, "BRI_HI": 150,
54
+ "REDNESS_MIN": 12, "REJECT_THR": 0.55, "use_model": True},
55
+ "mobile": {"AREA_MIN": 0.05, "BLUR_MIN": 7, "BRI_LO": 22, "BRI_HI": 220,
56
+ "REDNESS_MIN": 6, "REJECT_THR": 0.9, "use_model": False}}})
57
+ QIMG = int(QCFG.get("QIMG", 384))
58
+
59
+ # ------------------------------------------------------------------ models
60
+ def build_dr():
61
+ return timm.create_model(BACKBONE, pretrained=False, num_classes=1,
62
+ drop_rate=0.3, drop_path_rate=0.2).to(DEVICE).eval()
63
 
64
+ MEMBERS, QMODEL, UNET, CALIB = [], None, None, None
 
 
 
 
65
 
 
66
  def load_models():
67
+ global MEMBERS, QMODEL, UNET, CALIB
68
+ # --- DR ensemble (v3 + v4) ---
69
  MEMBERS = []
70
+ for p in sorted(MODELS_DIR.glob("*best*.pt")) + sorted(MODELS_DIR.glob("best*.pt")):
71
+ if p in [getattr(m, "_path", None) for m in MEMBERS]: continue
72
+ try:
73
+ m = build_dr(); sd = torch.load(str(p), map_location=DEVICE)
74
+ if isinstance(sd, dict) and "state_dict" in sd: sd = sd["state_dict"]
75
+ m.load_state_dict(sd); m._path = p; MEMBERS.append(m); print(f"[dr] {p.name}")
76
+ except Exception as e: print(f"[dr] skip {p.name}: {e}")
77
+ # --- quality gate (EfficientNet-B0 3-class) ---
78
+ qp = MODELS_DIR / "quality_gate.pt"
79
+ if qp.exists():
80
+ try:
81
+ QMODEL = timm.create_model("efficientnet_b0", pretrained=False, num_classes=3, drop_rate=0.2).to(DEVICE).eval()
82
+ sd = torch.load(str(qp), map_location=DEVICE)
83
+ if isinstance(sd, dict) and "state_dict" in sd: sd = sd["state_dict"]
84
+ QMODEL.load_state_dict(sd); print("[quality] loaded")
85
+ except Exception as e: QMODEL = None; print(f"[quality] skip: {e}")
86
+ # --- UNet++ lesion ---
87
+ up = MODELS_DIR / "unet_lesion_v2.pt"
88
+ if up.exists():
89
+ try:
90
+ import segmentation_models_pytorch as smp
91
+ UNET = smp.UnetPlusPlus("efficientnet-b4", encoder_weights=None, in_channels=3, classes=4).to(DEVICE).eval()
92
+ sd = torch.load(str(up), map_location=DEVICE)
93
+ if isinstance(sd, dict) and "state_dict" in sd: sd = sd["state_dict"]
94
+ UNET.load_state_dict(sd); print("[unet] loaded")
95
+ except Exception as e: UNET = None; print(f"[unet] skip: {e}")
96
+ # --- calibrator (isotonic) ---
97
+ cp = CONFIG_DIR / "calibrator.pkl"
98
+ if cp.exists():
99
+ try:
100
+ import joblib; CALIB = joblib.load(str(cp)); print("[calib] loaded")
101
+ except Exception as e: CALIB = None; print(f"[calib] skip: {e}")
102
+ print(f"[ready] dr={len(MEMBERS)} quality={QMODEL is not None} unet={UNET is not None} calib={CALIB is not None} device={DEVICE}")
103
+
104
  load_models()
105
 
106
  # ------------------------------------------------------------------ preprocessing
107
+ def _crop_bbox(bgr, tol=7):
108
+ g = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY); m = g > tol
109
+ if m.sum() == 0: return 0, 0, bgr.shape[0], bgr.shape[1]
110
+ c = np.argwhere(m); y0, x0 = c.min(0); y1, x1 = c.max(0) + 1
111
+ return int(y0), int(x0), int(y1), int(x1)
 
 
112
 
113
+ def _clahe(bgr):
114
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB); l, a, b = cv2.split(lab)
115
  l = cv2.createCLAHE(2.0, (8, 8)).apply(l)
116
  return cv2.cvtColor(cv2.merge((l, a, b)), cv2.COLOR_LAB2BGR)
117
 
118
+ def dr_preprocess(bgr):
119
+ y0, x0, y1, x1 = _crop_bbox(bgr); img = bgr[y0:y1, x0:x1]
120
  if img.size == 0: img = bgr
121
+ img = _clahe(cv2.resize(img, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_AREA))
122
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
 
123
 
124
  def to_tensor(rgb):
125
  x = ((rgb / 255.0 - _MEAN) / _STD).transpose(2, 0, 1).astype(np.float32)
126
  return torch.from_numpy(x).unsqueeze(0).to(DEVICE)
127
 
128
+ def crop_resize(bgr, work, clahe=True):
129
+ """crop fundus + resize (max side=work). คืน rgb + bbox สำหรับ warp กลับ"""
130
+ y0, x0, y1, x1 = _crop_bbox(bgr); crop = bgr[y0:y1, x0:x1]
131
+ if crop.size == 0: crop = bgr; y0, x0, y1, x1 = 0, 0, bgr.shape[0], bgr.shape[1]
132
+ h, w = crop.shape[:2]; s = work / max(h, w)
133
+ r = cv2.resize(crop, (int(w * s), int(h * s)), interpolation=cv2.INTER_AREA)
134
+ if clahe: r = _clahe(r)
135
+ return cv2.cvtColor(r, cv2.COLOR_BGR2RGB), (y0, x0, y1, x1)
136
+
137
+ # ------------------------------------------------------------------ quality gate
138
+ def fundus_metrics(bgr):
139
+ y0, x0, y1, x1 = _crop_bbox(bgr); crop = bgr[y0:y1, x0:x1]
140
+ if crop.size == 0: crop = bgr
141
+ g = cv2.cvtColor(cv2.resize(crop, (QIMG, QIMG)), cv2.COLOR_BGR2GRAY)
142
+ blur = float(cv2.Laplacian(g, cv2.CV_64F).var())
143
+ bright = float(g.mean())
144
+ fg = (cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY) > 7).mean()
145
+ rgb = cv2.cvtColor(cv2.resize(bgr, (256, 256)), cv2.COLOR_BGR2RGB).astype(float)
146
+ redness = float(rgb[:, :, 0].mean() - rgb[:, :, 2].mean())
147
+ return {"area_ratio": float(fg), "blur": blur, "bright": bright, "redness": redness}
148
 
149
+ @torch.no_grad()
150
+ def quality_prob_reject(bgr):
151
+ if QMODEL is None: return None
152
+ y0, x0, y1, x1 = _crop_bbox(bgr); crop = bgr[y0:y1, x0:x1]
153
+ if crop.size == 0: crop = bgr
154
+ rgb = cv2.cvtColor(cv2.resize(crop, (QIMG, QIMG), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2RGB)
155
+ x = to_tensor(rgb)
156
+ return float(torch.softmax(QMODEL(x), 1)[0, 2].cpu()) # P(Reject)
157
+
158
+ def check_quality(bgr, profile):
159
+ pf = QCFG["profiles"].get(profile, QCFG["profiles"][QCFG["default_profile"]])
160
+ m = fundus_metrics(bgr)
161
+ if m["redness"] < pf["REDNESS_MIN"] or m["area_ratio"] < pf["AREA_MIN"]:
162
+ return {"ok": False, "stage": "heuristic", "reason_th": "ไม่ใช่ภาพจอประสาทตา / ถ่ายไม่ติดจอ",
163
+ "reason_en": "Not a fundus image / retina not captured", "metrics": m}
164
+ if m["blur"] < pf["BLUR_MIN"]:
165
+ return {"ok": False, "stage": "heuristic", "reason_th": "ภาพเบลอเกินไป ถ่ายใหม่",
166
+ "reason_en": "Image too blurry, retake", "metrics": m}
167
+ if not (pf["BRI_LO"] <= m["bright"] <= pf["BRI_HI"]):
168
+ return {"ok": False, "stage": "heuristic", "reason_th": "ภาพมืด/สว่างเกินไป ถ่ายใหม่",
169
+ "reason_en": "Image too dark/bright, retake", "metrics": m}
170
+ qrej = None
171
+ if pf.get("use_model", True) and QMODEL is not None:
172
+ qrej = quality_prob_reject(bgr)
173
+ if qrej is not None and qrej >= pf["REJECT_THR"]:
174
+ return {"ok": False, "stage": "model", "reason_th": "ภาพไม่ชัดพอสำหรับวินิจฉัย ถ่ายใหม่",
175
+ "reason_en": "Image quality insufficient, retake", "metrics": m, "p_reject": round(qrej, 3)}
176
+ return {"ok": True, "stage": "passed", "metrics": m,
177
+ "p_reject": round(qrej, 3) if qrej is not None else None}
178
+
179
+ # ------------------------------------------------------------------ screening (ensemble + calibration)
180
  @torch.no_grad()
181
  def ensemble_score(x):
182
  ss = []
 
186
  ss.append(float((o / 3).item()))
187
  return float(np.mean(ss))
188
 
189
+ def calibrate(score):
190
+ if CALIB is not None:
191
+ try: return float(np.clip(CALIB.predict([score])[0], 0, 1))
192
+ except Exception: pass
193
+ return float(1 / (1 + np.exp(-(score - ROUNDER_COEFS[1]) * 2.2))) # fallback sigmoid
194
+
195
+ def decide_zone(prob, grade):
196
+ # grade-anchored เพื่อความสอดคล้อง: referable DR = grade>=2 (Moderate ขึ้นไป)
197
+ if grade >= 2: return "refer"
198
+ if prob >= P_HI: return "review" # No DR/Mild แต่โมเดลเสี่ยงสูง -> ให้คนตรวจซ้ำ
199
+ return "normal"
200
+
201
+ def grade_from_score(s):
202
+ return int(np.clip(np.digitize([s], ROUNDER_COEFS)[0], 0, 4))
203
+
204
+ # ------------------------------------------------------------------ lesion (UNet) + landmarks
205
+ @torch.no_grad()
206
+ def predict_full(rgb):
207
+ H, W = rgb.shape[:2]; st = PATCH // 2
208
+ prob = np.zeros((4, H, W), np.float32); cnt = np.zeros((H, W), np.float32)
209
+ ys = list(range(0, max(1, H - PATCH + 1), st)); xs = list(range(0, max(1, W - PATCH + 1), st))
210
+ if H > PATCH and ys[-1] != H - PATCH: ys.append(H - PATCH)
211
+ if W > PATCH and xs[-1] != W - PATCH: xs.append(W - PATCH)
212
+ for y in ys:
213
+ for x in xs:
214
+ p = rgb[y:y + PATCH, x:x + PATCH]
215
+ xt = torch.from_numpy(((p / 255.0 - _MEAN) / _STD).transpose(2, 0, 1).astype(np.float32)).unsqueeze(0).to(DEVICE)
216
+ pr = torch.sigmoid(UNET(xt))[0].float().cpu().numpy()
217
+ prob[:, y:y + PATCH, x:x + PATCH] += pr; cnt[y:y + PATCH, x:x + PATCH] += 1
218
+ return prob / np.maximum(cnt, 1e-6)
219
+
220
+ def lesion_features(prob, rgb=None, thr=0.5):
221
+ C, H, W = prob.shape; feats, masks = {}, {}
222
+ gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) if rgb is not None else None
223
+ bt = float(np.percentile(gray[gray > 10], 55)) if gray is not None and (gray > 10).any() else None
224
+ for ci, les in enumerate(LESIONS):
225
+ mk = (prob[ci] > thr).astype(np.uint8)
226
+ if bt is not None and les in ("EX", "SE"): # bright lesions: ตัดบริเวณมืด (กัน fovea false-EX)
227
+ mk = (mk & (gray > bt).astype(np.uint8)).astype(np.uint8)
228
+ masks[les] = mk
229
+ n, lbl, stats, _ = cv2.connectedComponentsWithStats(mk, 8)
230
+ comps = [int(stats[k, cv2.CC_STAT_AREA]) for k in range(1, n) if stats[k, cv2.CC_STAT_AREA] >= MIN_AREA]
231
+ area = int(sum(comps))
232
+ feats[les] = {"count": len(comps), "area_px": area, "area_pct": round(100.0 * area / (H * W), 3)}
233
+ return feats, masks
234
+
235
+ def quadrant_spread(mask):
236
+ H, W = mask.shape; my, mx = H // 2, W // 2
237
+ q = {"บนซ้าย": mask[:my, :mx], "บนขวา": mask[:my, mx:], "ล่างซ้าย": mask[my:, :mx], "ล่างขวา": mask[my:, mx:]}
238
+ return [k for k, v in q.items() if v.sum() >= MIN_AREA]
239
+
240
+ def detect_disc(rgb):
241
+ H, W = rgb.shape[:2]; gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
242
+ fg = gray > 10; blur = cv2.GaussianBlur(gray, (0, 0), max(3.0, W * 0.015))
243
+ _, _, _, (cx, cy) = cv2.minMaxLoc(np.where(fg, blur, -1.0))
244
+ r = int(0.05 * W)
245
  try:
246
+ t = np.percentile(blur[fg], 99.0); bright = ((blur >= t) & fg).astype(np.uint8)
247
+ n, lbl, stats, cent = cv2.connectedComponentsWithStats(bright, 8)
248
+ if n > 1:
249
+ lab = lbl[cy, cx]
250
+ if lab == 0: lab = min(range(1, n), key=lambda i: (cent[i][0] - cx) ** 2 + (cent[i][1] - cy) ** 2)
251
+ r = int(np.clip(np.sqrt(stats[lab, cv2.CC_STAT_AREA] / np.pi), 0.03 * W, 0.12 * W))
252
+ except Exception: pass
253
+ return int(cx), int(cy), int(r)
254
+
255
+ def detect_fovea(rgb, disc):
256
+ H, W = rgb.shape[:2]; cx, cy, r = disc; DD = 2 * r
257
+ gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32); fg = (gray > 10).astype(np.uint8)
258
+ ys0, xs0 = np.where(fg > 0); gx = xs0.mean() if len(xs0) else W / 2
259
+ sidex = 1.0 if (gx - cx) >= 0 else -1.0
260
+ fg_e = cv2.erode(fg, np.ones((max(3, int(0.6 * DD)),) * 2, np.uint8), 1).astype(bool)
261
+ blur = cv2.GaussianBlur(gray, (0, 0), max(3.0, DD * 0.35))
262
+ yy, xx = np.mgrid[0:H, 0:W]; dist = np.sqrt((xx - cx) ** 2 + (yy - cy) ** 2)
263
+ band = fg_e & (dist > 1.5 * DD) & (dist < 3.5 * DD) & (np.abs(yy - cy) < 1.3 * DD) & (np.sign(xx - cx) == sidex)
264
+ if band.sum() < 50: band = fg_e & (dist > 1.2 * DD) & (dist < 4.0 * DD) & (np.sign(xx - cx) == sidex)
265
+ if band.sum() < 50: band = fg_e & (dist > 1.0 * DD)
266
+ if band.sum() < 50: band = fg_e
267
+ fy, fx = np.unravel_index(int(np.argmin(np.where(band, blur, 1e9))), (H, W))
268
+ return int(fx), int(fy)
269
+
270
+ def fovea_metrics(masks, fovea, DD):
271
+ fx, fy = fovea; out = {}
272
+ for les in LESIONS:
273
+ ys, xs = np.where(masks[les] > 0)
274
+ if len(xs) == 0: out[les] = {"min_dd": None}; continue
275
+ d = np.sqrt((xs - fx) ** 2 + (ys - fy) ** 2) / max(DD, 1)
276
+ out[les] = {"min_dd": round(float(d.min()), 2)}
277
+ return out
278
 
279
+ def build_rationale(feats, masks, fov, grade_name):
280
+ bits = []
281
+ if feats["MA"]["count"] > 0: bits.append(f"microaneurysm ~{feats['MA']['count']} จุด")
282
+ he = feats["HE"]
283
+ if he["area_px"] > 0:
284
+ q = quadrant_spread(masks["HE"])
285
+ bits.append(f"hemorrhage {he['count']} ก้อน กระจาย {len(q)} quadrant (~{he['area_pct']}% ของจอ)")
286
+ ex = feats["EX"]
287
+ if ex["area_px"] > 0:
288
+ d = fov["EX"]["min_dd"]
289
+ loc = (f"ใกล้ fovea ~{d} DD — ภายใน 1 DD เสี่ยง CSME" if d is not None and d <= 1.0
290
+ else (f"ห่าง fovea ~{d} DD" if d is not None else ""))
291
+ bits.append(f"hard exudate ~{ex['area_pct']}% {loc}".strip())
292
+ if feats["SE"]["area_px"] > 0: bits.append("soft exudate / cotton-wool spot")
293
+ if not bits: return "segmentation ไม่พบรอยโรคชัดเจน (รอยเล็กมากอาจตรวจไม่พบ)"
294
+ head = f"เหตุผลประกอบ (จัดเป็น {grade_name}): " if grade_name else "รอยโรคที่ตรวจพบ: "
295
+ return head + "; ".join(bits)
296
+
297
+ # ------------------------------------------------------------------ rendering layers
298
+ def _png_b64(img_bgr_or_bgra):
299
+ ok, buf = cv2.imencode(".png", img_bgr_or_bgra)
300
  return base64.b64encode(buf).decode() if ok else None
301
 
302
+ def make_layers(raw_rgb, enh_rgb, masks, disc, fovea):
303
+ """raw base, enhanced base, lesion layer (RGBA โปร่งใส), landmark layer (RGBA)"""
304
+ H, W = raw_rgb.shape[:2]
305
+ base_raw = _png_b64(cv2.cvtColor(raw_rgb, cv2.COLOR_RGB2BGR))
306
+ base_enh = _png_b64(cv2.cvtColor(enh_rgb, cv2.COLOR_RGB2BGR))
307
+ # lesion layer
308
+ les = np.zeros((H, W, 4), np.uint8)
309
+ for k in ["HE", "EX", "SE"]: # ปื้น = mask โปร่งแสง
310
+ m = masks[k].astype(bool); c = PALETTE[k]
311
+ les[m] = (c[0], c[1], c[2], 200)
312
+ ys, xs = np.where(masks["MA"] > 0) # MA = จุด marker
313
+ for x, y in zip(xs[::3], ys[::3]):
314
+ cv2.circle(les, (int(x), int(y)), max(2, int(0.004 * W)), (255, 0, 0, 255), -1)
315
+ les_bgra = cv2.cvtColor(les, cv2.COLOR_RGBA2BGRA)
316
+ # landmark layer
317
+ lm = np.zeros((H, W, 4), np.uint8); cx, cy, r = disc; fx, fy = fovea; DD = 2 * r
318
+ cv2.circle(lm, (cx, cy), r, (0, 255, 255, 255), 2)
319
+ s = max(6, int(0.03 * W))
320
+ cv2.line(lm, (fx - s, fy), (fx + s, fy), (255, 0, 255, 255), 2)
321
+ cv2.line(lm, (fx, fy - s), (fx, fy + s), (255, 0, 255, 255), 2)
322
+ for kk in (1, 2): cv2.circle(lm, (fx, fy), int(kk * DD), (255, 255, 255, 160), 1)
323
+ lm_bgra = cv2.cvtColor(lm, cv2.COLOR_RGBA2BGRA)
324
+ return {"raw": base_raw, "enhanced": base_enh,
325
+ "lesion": _png_b64(les_bgra), "landmark": _png_b64(lm_bgra)}
326
+
327
+ def explain_lesions(bgr, grade_name):
328
+ enh_rgb, _ = crop_resize(bgr, WORK, clahe=True)
329
+ raw_rgb, _ = crop_resize(bgr, WORK, clahe=False)
330
+ prob = predict_full(enh_rgb)
331
+ feats, masks = lesion_features(prob, enh_rgb)
332
+ disc = detect_disc(enh_rgb); fovea = detect_fovea(enh_rgb, disc); DD = 2 * disc[2]
333
+ fov = fovea_metrics(masks, fovea, DD)
334
+ layers = make_layers(raw_rgb, enh_rgb, masks, disc, fovea)
335
+ rationale = build_rationale(feats, masks, fov, grade_name)
336
+ return {"features": feats, "fovea_metrics": fov, "layers": layers,
337
+ "disc": list(disc), "fovea": list(fovea), "rationale": rationale}
338
+
339
+ def raw_only_layer(bgr):
340
+ return {"raw": _png_b64(cv2.cvtColor(crop_resize(bgr, WORK, clahe=False)[0], cv2.COLOR_RGB2BGR))}
341
 
342
+ # ------------------------------------------------------------------ history
343
  def load_history(limit=200):
344
  if HISTORY_FILE.exists():
345
  try: return json.loads(HISTORY_FILE.read_text(encoding="utf-8"))[:limit]
346
  except Exception: return []
347
  return []
348
 
349
+ def save_history(rec):
350
+ try:
351
+ data = load_history(); data.insert(0, rec)
352
+ HISTORY_FILE.write_text(json.dumps(data[:200], ensure_ascii=False), encoding="utf-8")
353
+ except Exception: pass
354
+
355
  # ------------------------------------------------------------------ flask
356
  app = Flask(__name__, static_folder=".", static_url_path="")
357
  CORS(app)
 
365
 
366
  @app.route("/<path:f>")
367
  def assets(f):
368
+ return send_from_directory(".", f) if (HERE / f).is_file() else ("", 404)
 
369
 
370
  @app.route("/status")
371
  def status():
372
+ return jsonify({"ok": True, "dr_models": len(MEMBERS), "quality": QMODEL is not None,
373
+ "lesion": UNET is not None, "calibrated": CALIB is not None,
374
+ "device": DEVICE, "demo": len(MEMBERS) == 0,
375
+ "profiles": {k: v.get("label_th", k) for k, v in QCFG["profiles"].items()}})
376
+
377
+ ZONE_TH = {"normal": "ปกติ — ไม่ต้องส่งต่อ", "review": "ไม่แน่ใจ — ให้ผู้เชี่ยวชาญตรวจซ้ำ", "refer": "พบความผิดปกติ — ส่งต่อจักษุแพทย์"}
378
+ ZONE_EN = {"normal": "Normal — no referral", "review": "Uncertain — needs human review", "refer": "Refer to ophthalmologist"}
379
 
380
  @app.route("/predict", methods=["POST"])
381
  def predict():
382
  try:
383
+ if "image" not in request.files: return jsonify({"error": "no image"}), 400
 
384
  raw = np.frombuffer(request.files["image"].read(), np.uint8)
385
  bgr = cv2.imdecode(raw, cv2.IMREAD_COLOR)
386
  if bgr is None: return jsonify({"error": "bad image"}), 400
387
+ profile = request.form.get("mode", QCFG.get("default_profile", "fundus"))
388
 
389
+ # --- stage 0: quality gate ---
390
+ q = check_quality(bgr, profile)
391
+ if not q["ok"]:
392
+ return jsonify({"not_gradable": True, "mode": profile, "quality": q,
393
+ "message_th": q["reason_th"], "message_en": q["reason_en"]})
 
394
 
395
+ # --- stage 1: screening (ensemble + calibration) ---
396
+ if len(MEMBERS) == 0:
397
+ score, demo = 1.9, True
398
  else:
399
+ score = ensemble_score(to_tensor(dr_preprocess(bgr))); demo = False
400
+ prob = calibrate(score); grade = grade_from_score(score); zone = decide_zone(prob, grade)
401
+
402
+ res = {"demo": demo, "mode": profile, "quality": q,
403
+ "grade": grade, "grade_name": CLASS_NAMES[grade], "score": round(score, 2),
404
+ "risk_percent": round(prob * 100, 1), "zone": zone,
405
+ "zone_th": ZONE_TH[zone], "zone_en": ZONE_EN[zone],
406
+ "referable": zone == "refer"}
407
+
408
+ # lesion explain แยกไป /explain (lazy) — คัดกรองตอบเร็ว ส่งแค่ภาพดิบมาก่อน
409
+ res["layers"] = raw_only_layer(bgr)
410
+ res["lesion_available"] = UNET is not None
411
+
 
 
 
 
 
412
  save_history({"time": datetime.datetime.now().isoformat(timespec="seconds"),
413
+ "grade": grade, "grade_name": CLASS_NAMES[grade], "zone": zone,
414
+ "referable": zone == "refer", "risk_percent": round(prob * 100, 1)})
415
  return jsonify(res)
416
  except Exception as e:
417
+ traceback.print_exc(); return jsonify({"error": str(e)}), 500
418
+
419
+ @app.route("/explain", methods=["POST"])
420
+ def explain_route():
421
+ """lazy lesion — เรียกตอนเปิด deep-dive เท่านั้น (UNet + disc/fovea + overlay layers)"""
422
+ try:
423
+ if "image" not in request.files: return jsonify({"error": "no image"}), 400
424
+ raw = np.frombuffer(request.files["image"].read(), np.uint8)
425
+ bgr = cv2.imdecode(raw, cv2.IMREAD_COLOR)
426
+ if bgr is None: return jsonify({"error": "bad image"}), 400
427
+ if UNET is None: return jsonify({"lesion_unavailable": True})
428
+ return jsonify(explain_lesions(bgr, request.form.get("grade_name", "")))
429
+ except Exception as e:
430
+ traceback.print_exc(); return jsonify({"error": str(e)}), 500
431
 
432
  @app.route("/history")
433
  def history(): return jsonify(load_history())
434
 
435
  @app.route("/stats")
436
  def stats():
437
+ h = load_history(); n = len(h)
 
438
  dist = {c: 0 for c in CLASS_NAMES}
439
  for x in h: dist[x.get("grade_name", "No DR")] = dist.get(x.get("grade_name", "No DR"), 0) + 1
440
+ ref = sum(1 for x in h if x.get("referable") or x.get("zone") == "refer")
441
+ review = sum(1 for x in h if x.get("zone") == "review")
442
+ return jsonify({"total": n, "referable": ref, "refer": ref, "review": review,
443
+ "normal": n - ref, "dist": dist})
444
 
445
  if __name__ == "__main__":
446
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)), debug=True)
 
config/calibrator.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2182ba63872660e3bb0cc614604f4a5c82c8e0b0aa147807b0cb12af0e03e8b
3
+ size 1975
config/classes.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "0": "No DR",
3
+ "1": "Mild",
4
+ "2": "Moderate",
5
+ "3": "Severe",
6
+ "4": "Proliferative"
7
+ }
config/quality_gate_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "QIMG": 384,
3
+ "classes": ["Good", "Usable", "Reject"],
4
+ "default_profile": "fundus",
5
+ "profiles": {
6
+ "fundus": {
7
+ "label_th": "กล้องจอตามาตรฐาน",
8
+ "AREA_MIN": 0.28,
9
+ "BLUR_MIN": 8.0,
10
+ "BRI_LO": 35.0,
11
+ "BRI_HI": 160.0,
12
+ "REDNESS_MIN": 10.0,
13
+ "REJECT_THR": 0.75,
14
+ "use_model": true
15
+ },
16
+ "mobile": {
17
+ "label_th": "มือถือ + เลนส์ 20D",
18
+ "AREA_MIN": 0.05,
19
+ "BLUR_MIN": 7.0,
20
+ "BRI_LO": 22.0,
21
+ "BRI_HI": 220.0,
22
+ "REDNESS_MIN": 6.0,
23
+ "REJECT_THR": 0.90,
24
+ "use_model": false
25
+ }
26
+ },
27
+ "_note": "fundus = ค่าจาก EyeQ (tabletop). mobile = ผ่อนเกณฑ์ + ปิด EyeQ model (เทรนบน tabletop จะ over-reject ภาพ 20D) ใช้ heuristic อย่างเดียว รอ recalibrate ด้วยภาพ 20D จริง"
28
+ }
config/thresholds.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "P_LO": 0.029213483146067417,
3
+ "P_HI": 0.3333333333333333,
4
+ "sens_target": 0.95,
5
+ "spec_target": 0.95,
6
+ "rounder_coefs": [
7
+ 0.515,
8
+ 1.264,
9
+ 2.376,
10
+ 3.079
11
+ ],
12
+ "referable_thr": 1.264,
13
+ "report": [
14
+ {
15
+ "dataset": "ddr",
16
+ "n": 12522,
17
+ "automation_rate": 0.6483788532183358,
18
+ "abstain_rate": 0.3516211467816643,
19
+ "auto_sens": 0.9779049122114816,
20
+ "auto_spec": 0.8265573770491803
21
+ },
22
+ {
23
+ "dataset": "idrid",
24
+ "n": 455,
25
+ "automation_rate": 0.8703296703296703,
26
+ "abstain_rate": 0.12967032967032968,
27
+ "auto_sens": 1.0,
28
+ "auto_spec": 0.5104166666666666
29
+ },
30
+ {
31
+ "dataset": "test",
32
+ "n": 9261,
33
+ "automation_rate": 0.644638807904114,
34
+ "abstain_rate": 0.35536119209588596,
35
+ "auto_sens": 0.9413965087281796,
36
+ "auto_spec": 0.9216674301420064
37
+ }
38
+ ]
39
+ }
detect.css CHANGED
@@ -207,4 +207,102 @@
207
  .tip i{font-size:26px;color:var(--brand);display:block;margin-bottom:9px}
208
  .tip b{display:block;font-size:14.5px;font-weight:700;margin-bottom:3px;color:var(--text)}
209
  .tip span{font-size:12.5px;color:var(--text-2);line-height:1.5}
210
- @media(max-width:600px){.tips-row{grid-template-columns:1fr}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  .tip i{font-size:26px;color:var(--brand);display:block;margin-bottom:9px}
208
  .tip b{display:block;font-size:14.5px;font-weight:700;margin-bottom:3px;color:var(--text)}
209
  .tip span{font-size:12.5px;color:var(--text-2);line-height:1.5}
210
+ @media(max-width:600px){.tips-row{grid-template-columns:1fr}}
211
+ /* ===== mode selector ===== */
212
+ .mode-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:12px 16px}
213
+ .mode-lbl{font-size:13px;color:var(--text-2);font-weight:500;display:flex;align-items:center;gap:6px}
214
+ .mode-opt{display:inline-flex;align-items:center;gap:6px;font-size:13px;padding:8px 14px;border-radius:11px;border:1.5px solid var(--line);background:var(--surface);color:var(--text-2);cursor:pointer;transition:.15s}
215
+ .mode-opt:hover{border-color:var(--brand)}
216
+ .mode-opt.active{border-color:var(--brand);background:var(--brand-soft);color:var(--brand-d);font-weight:600}
217
+
218
+ /* ===== result layout ===== */
219
+ .result-main{display:grid;grid-template-columns:1.15fr .85fr;gap:16px}
220
+ @media(max-width:760px){.result-main{grid-template-columns:1fr}}
221
+
222
+ /* ===== layered viewer ===== */
223
+ .viewer .stack{position:relative;width:100%;margin:10px 0;border-radius:14px;overflow:hidden;background:#000;line-height:0}
224
+ .lyr-img{display:block;width:100%}
225
+ .lyr-img.ov{position:absolute;inset:0;pointer-events:none}
226
+ .viewer-ctrl{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
227
+ .lyr-btn{display:inline-flex;align-items:center;gap:5px;font-size:12px;padding:6px 11px;border-radius:9px;border:1px solid var(--line);background:var(--surface);color:var(--text-2);cursor:pointer}
228
+ .lyr-btn.on{border-color:var(--brand);background:var(--brand-soft);color:var(--brand-d);font-weight:600}
229
+ .lyr-btn.disabled{opacity:.4;cursor:not-allowed}
230
+ .vsep{width:1px;height:20px;background:var(--line)}
231
+ .op-wrap{display:flex;align-items:center;gap:7px;font-size:12px;color:var(--text-2);margin-left:auto}
232
+ .op-wrap input[type=range]{width:88px}
233
+ .legend{display:flex;gap:14px;margin-top:11px;font-size:12px;color:var(--text-2)}
234
+ .legend span{display:inline-flex;align-items:center;gap:5px}
235
+ .legend .dot{width:11px;height:11px;border-radius:3px;display:inline-block}
236
+
237
+ /* ===== report panel ===== */
238
+ .report .stage-mini{margin-bottom:14px}
239
+ .rep-lbl{margin:4px 0 8px}
240
+ .findings{display:flex;flex-direction:column}
241
+ .frow{display:flex;justify-content:space-between;align-items:baseline;padding:8px 0;border-bottom:1px solid var(--line);font-size:13.5px}
242
+ .frow .fl{color:var(--text-2)}
243
+ .frow .fv{font-weight:600}
244
+ .frow .fv.warn{color:var(--danger)}
245
+ .warnbox{display:flex;align-items:center;gap:7px;background:var(--warn-soft);color:var(--warn);font-size:12.5px;padding:9px 11px;border-radius:10px;margin-top:11px}
246
+ .why2{display:flex;gap:9px;margin-top:12px;font-size:13px;color:var(--text-2);line-height:1.6}
247
+ .why2 i{color:var(--brand);font-size:18px;flex-shrink:0}
248
+ .verdict.warn .vt h2{color:var(--warn)}
249
+
250
+ /* ===== screener-first layout (responsive) ===== */
251
+ .result{max-width:640px;margin:0 auto;width:100%}
252
+ .viewer .stack{max-width:470px;margin:12px auto 4px}
253
+ .viewer .lbl{justify-content:center}
254
+
255
+ /* verdict — premium hero */
256
+ .verdict{flex-wrap:wrap;row-gap:10px}
257
+ .verdict .vt h2{font-size:22px;line-height:1.2}
258
+ .verdict .vp b{font-size:32px}
259
+
260
+ /* deep-dive toggle */
261
+ .deepbtn{width:100%;display:flex;align-items:center;justify-content:space-between;gap:10px;
262
+ padding:14px 18px;border:1px solid var(--line);border-radius:var(--r);background:var(--surface);
263
+ color:var(--text);font-size:14.5px;font-weight:600;cursor:pointer;transition:.15s;margin-top:2px}
264
+ .deepbtn:hover{border-color:var(--brand);background:var(--brand-soft)}
265
+ .deepbtn .db-l{display:flex;align-items:center;gap:9px}
266
+ .deepbtn .db-l i{color:var(--brand);font-size:19px}
267
+ .db-chev{transition:transform .25s var(--ease);color:var(--text-3)}
268
+ .deepbtn.open .db-chev{transform:rotate(180deg)}
269
+
270
+ /* deep-dive panel */
271
+ .deepdive{margin-top:12px}
272
+ .deepdive>.card,.deepdive .dd-grid{margin-bottom:14px}
273
+ .deepdive>.card:last-child{margin-bottom:0}
274
+ .dd-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
275
+ @media(max-width:600px){.dd-grid{grid-template-columns:1fr}}
276
+ .dd-card .lbl{margin-bottom:11px}
277
+ .why2{margin-top:0}
278
+
279
+ @media(max-width:520px){
280
+ .verdict .vt h2{font-size:19px}
281
+ .verdict .vi{width:48px;height:48px;font-size:26px}
282
+ .verdict .vp b{font-size:26px}
283
+ .viewer-ctrl{gap:6px}.op-wrap{margin-left:0;width:100%}
284
+ }
285
+
286
+ /* ===== spacing polish (cards had no base padding) ===== */
287
+ .viewer{padding:16px 18px}
288
+ .dd-card{padding:18px 20px}
289
+ .deepbtn{padding:16px 20px}
290
+ .frow{padding:11px 2px}
291
+ .deepdive{margin-top:14px}
292
+ .deepdive>.card,.deepdive .dd-grid{margin-bottom:16px}
293
+ .legend{margin-top:13px;gap:16px}
294
+ .viewer-ctrl{gap:8px;row-gap:9px}
295
+ .warnbox{padding:11px 13px;margin-top:13px}
296
+ .why2{padding:2px}
297
+ @media(max-width:560px){
298
+ .det{padding:32px 16px 50px}
299
+ .viewer,.dd-card{padding:15px 16px}
300
+ .deepbtn{padding:15px 16px}
301
+ .verdict{padding:18px 18px}
302
+ .frow{font-size:13px}
303
+ }
304
+
305
+ /* lazy lesion loading */
306
+ .lesion-loading{display:flex;align-items:center;gap:8px;color:var(--text-2);font-size:13px;padding:10px 0}
307
+ .lesion-loading .spin{animation:lspin .9s linear infinite;display:inline-block;font-size:18px;color:var(--brand)}
308
+ @keyframes lspin{to{transform:rotate(360deg)}}
detect.html CHANGED
@@ -64,6 +64,13 @@
64
  <span data-th="โหมดสาธิต" data-en="Demo mode">โหมดสาธิต</span></span>
65
  </div>
66
 
 
 
 
 
 
 
 
67
  <!-- choose: camera or upload -->
68
  <div id="chooser" class="card chooser reveal d1">
69
  <button class="choice" id="tabCam"><i class="ti ti-camera"></i>
@@ -111,23 +118,62 @@
111
 
112
  <!-- result -->
113
  <div id="result" class="result" style="display:none">
 
114
  <div id="verdict" class="card verdict"></div>
115
- <div class="card stage-card">
116
- <div class="lbl" data-th="ระดับความรุนแรง (โดยประมาณ)" data-en="Estimated severity">ระดับความรุนแรง (โดยประมาณ)</div>
117
- <div class="stages" id="stages"></div>
118
- <div class="scorebar"><div class="scorebar-fill" id="scoreFill"></div></div>
119
- <div class="score-meta"><span>No DR</span><span id="scoreVal">score 0.0</span><span>Proliferative</span></div>
 
 
 
 
120
  </div>
121
- <div class="img-grid">
122
- <div class="card img-cell"><div class="lbl"><i class="ti ti-photo"></i> <span data-th="ภาพที่ประมวลผล" data-en="Processed image">ภาพที่ประมวลผล</span></div><img id="imgPre" alt=""></div>
123
- <div class="card img-cell"><div class="lbl"><i class="ti ti-flare"></i> <span data-th="บริเวณที่ AI วิเคราะห์" data-en="AI focus region">บริเวณที่ AI วิเคราะห์</span></div><img id="imgCam" alt=""><span class="cam-note" data-th="สีร้อน = AI ให้ความสำคัญ" data-en="Warm = AI attention">สีร้อน = AI ให้ความสำคัญ</span></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  </div>
125
- <div id="why" class="card why"></div>
126
  <div class="card disclaimer"><i class="ti ti-info-circle"></i>
127
- <span data-th="เครื่องมือคัดกรองเบื้องต้น ผลควรได้รับการยืนยันโดยจักษุแพทย์" data-en="A screening aid — confirm with an ophthalmologist.">เครื่องมือคัดกรองเบื้องต้น ผลควรได้รับการยืนยันโดยจักษุแพทย์</span></div>
128
  <div class="act">
129
  <button class="btn btn-ghost" id="again"><i class="ti ti-refresh"></i> <span data-th="ตรวจใหม่" data-en="Scan again">ตรวจใหม่</span></button>
130
- <button class="btn btn-primary" id="send"><i class="ti ti-send"></i> <span data-th="ส่งให้แพทย์" data-en="Send to doctor">ส่งให้แพทย์</span></button>
131
  </div>
132
  </div>
133
 
 
64
  <span data-th="โหมดสาธิต" data-en="Demo mode">โหมดสาธิต</span></span>
65
  </div>
66
 
67
+ <!-- image source mode (standard / mobile+20D) -->
68
+ <div id="modeRow" class="card mode-row reveal d1">
69
+ <span class="mode-lbl"><i class="ti ti-adjustments"></i> <span data-th="ชนิดภาพ" data-en="Image source">ชนิดภาพ</span></span>
70
+ <button class="mode-opt active" data-mode="fundus"><i class="ti ti-device-desktop"></i> <span data-th="กล้องจอตามาตรฐาน" data-en="Standard fundus camera">กล้องจอตามาตรฐาน</span></button>
71
+ <button class="mode-opt" data-mode="mobile"><i class="ti ti-device-mobile"></i> <span data-th="มือถือ + เลนส์ 20D" data-en="Phone + 20D lens">มือถือ + เลนส์ 20D</span></button>
72
+ </div>
73
+
74
  <!-- choose: camera or upload -->
75
  <div id="chooser" class="card chooser reveal d1">
76
  <button class="choice" id="tabCam"><i class="ti ti-camera"></i>
 
118
 
119
  <!-- result -->
120
  <div id="result" class="result" style="display:none">
121
+ <!-- screener-facing verdict (simple) -->
122
  <div id="verdict" class="card verdict"></div>
123
+
124
+ <!-- clean fundus image -->
125
+ <div class="card viewer" id="viewerCard">
126
+ <div class="lbl"><i class="ti ti-photo"></i> <span id="baseLbl" data-th="ภาพจอตา" data-en="Fundus image">ภาพจอตา</span></div>
127
+ <div class="stack" id="stack">
128
+ <img id="imgBase" class="lyr-img" alt="">
129
+ <img id="imgLesion" class="lyr-img ov" alt="">
130
+ <img id="imgLandmark" class="lyr-img ov" alt="">
131
+ </div>
132
  </div>
133
+
134
+ <!-- deep-dive toggle (for doctors) -->
135
+ <button class="deepbtn" id="deepBtn">
136
+ <span class="db-l"><i class="ti ti-stethoscope"></i> <span data-th="ข้อมูลเชิงลึกสำหรับแพทย์" data-en="Clinical details for doctors">ข้อมูลเชิงลึกสำหรับแพทย์</span></span>
137
+ <i class="ti ti-chevron-down db-chev" id="deepChev"></i>
138
+ </button>
139
+
140
+ <!-- deep-dive panel (collapsed) -->
141
+ <div id="deepdive" class="deepdive" style="display:none">
142
+ <div class="card dd-card">
143
+ <div class="lbl"><i class="ti ti-stack-2"></i> <span data-th="ชั้นภาพ (เปิด/ปิดได้)" data-en="Image layers (toggle)">ชั้นภาพ (เปิด/ปิดได้)</span></div>
144
+ <div class="viewer-ctrl">
145
+ <button class="lyr-btn" id="tgLesion"><i class="ti ti-eye"></i> <span data-th="รอยโรค" data-en="Lesions">รอยโรค</span></button>
146
+ <button class="lyr-btn" id="tgLandmark"><i class="ti ti-circle-dashed"></i> <span data-th="จุดอ้างอิง" data-en="Landmarks">จุดอ้างอิง</span></button>
147
+ <span class="vsep"></span>
148
+ <button class="lyr-btn on" id="baseRaw">Raw</button>
149
+ <button class="lyr-btn" id="baseEnh" data-th="ปรับชัด" data-en="Enhanced">ปรับชัด</button>
150
+ <span class="op-wrap"><span data-th="ความเข้ม" data-en="Opacity">ความเข้ม</span>
151
+ <input type="range" id="opacity" min="0" max="100" value="55" step="1"></span>
152
+ </div>
153
+ <div class="legend"><span><i class="dot" style="background:#e24b4a"></i>MA</span><span><i class="dot" style="background:#2f6fe0"></i>HE</span><span><i class="dot" style="background:#39b54a"></i>EX</span><span><i class="dot" style="background:#e0c000"></i>SE</span></div>
154
+ </div>
155
+
156
+ <div class="dd-grid">
157
+ <div class="card dd-card">
158
+ <div class="lbl"><i class="ti ti-chart-bar"></i> <span data-th="ระดับความรุนแรง" data-en="Severity">ระดับความรุนแรง</span></div>
159
+ <div class="stages" id="stages"></div>
160
+ <div class="scorebar"><div class="scorebar-fill" id="scoreFill"></div></div>
161
+ <div class="score-meta"><span>No DR</span><span id="scoreVal">score 0.0</span><span>Prolif.</span></div>
162
+ </div>
163
+ <div class="card dd-card">
164
+ <div class="lbl"><i class="ti ti-clipboard-text"></i> <span data-th="รายงานเชิงตัวเลข" data-en="Quantified findings">รายงานเชิงตัวเลข</span></div>
165
+ <div id="findings" class="findings"></div>
166
+ </div>
167
+ </div>
168
+
169
+ <div class="card dd-card"><div id="why" class="why2"></div></div>
170
  </div>
171
+
172
  <div class="card disclaimer"><i class="ti ti-info-circle"></i>
173
+ <span data-th="เครื่องมือช่วยตัดสินใจ ไม่ใช่การวินิจฉัยขั้นสุดท้าย — ผลต้องได้รับการยืนยันโดยจักษุแพทย์" data-en="Decision-support, not a final diagnosis — confirm with an ophthalmologist.">เครื่องมือช่วยตัดสินใจ ไม่ใช่การวินิจฉัยขั้นสุดท้าย — ผลต้องได้รับการยืนยันโดยจักษุแพทย์</span></div>
174
  <div class="act">
175
  <button class="btn btn-ghost" id="again"><i class="ti ti-refresh"></i> <span data-th="ตรวจใหม่" data-en="Scan again">ตรวจใหม่</span></button>
176
+ <button class="btn btn-primary" id="send"><i class="ti ti-send"></i> <span data-th="ส่งให้จักษุแพทย์" data-en="Send to ophthalmologist">ส่งให้จักษุแพทย์</span></button>
177
  </div>
178
  </div>
179
 
detect.js CHANGED
@@ -1,32 +1,25 @@
1
  const $ = s => document.querySelector(s);
2
  const STAGES = { th: ["No DR", "Mild", "Moderate", "Severe", "Proliferative"], en: ["No DR", "Mild", "Moderate", "Severe", "Proliferative"] };
3
  const TIPS = {
4
- th: {
5
- 0: 'ไม่พบลักษณะของเบาหวานขึ้นจอตา จอตาและเส้นเลือดอยู่ในเกณฑ์ปกติ',
6
- 1: 'พบสัญญาณเริ่มต้น เช่น microaneurysm เล็กน้อย แนะนำติดตามอาการ',
7
- 2: 'พบลักษณะระดับปานกลาง เช่น hard exudate / จุดเลือดออก',
8
- 3: 'พบความผิดปกติระดับรุนแรง ควรพบจักษุแพทย์โดยเร็ว',
9
- 4: 'พบลักษณะระยะลุกลาม (เส้นเลือดงอกผิดปกติ) ควรพบจักษุแพทย์ทันที'
10
- },
11
- en: {
12
- 0: 'No signs of diabetic retinopathy. Retina and vessels appear normal.',
13
- 1: 'Early signs such as a few microaneurysms. Monitoring recommended.',
14
- 2: 'Moderate features such as hard exudates / hemorrhages.',
15
- 3: 'Severe abnormalities. See an ophthalmologist soon.',
16
- 4: 'Proliferative features (abnormal new vessels). See an ophthalmologist now.'
17
- }
18
  };
19
  const T = (th, en) => getLang() === 'en' ? en : th;
20
 
21
  fetch('/status').then(r => r.json()).then(s => { if (s.demo) $('#modeTag').style.display = 'inline-flex'; }).catch(() => {});
22
-
23
- // dismiss splash (so it ไม่บัง clicks)
24
  setTimeout(() => { const s = document.getElementById('splash'); if (s) s.style.display = 'none'; }, 2500);
25
 
 
 
 
 
 
 
 
26
  // ---- tabs ----
27
  let stream = null, facing = 'environment';
28
- $('#tabUp').onclick = () => { setTab('up'); };
29
- $('#tabCam').onclick = () => { setTab('cam'); };
30
  function setTab(t) {
31
  $('#tabUp').classList.toggle('active', t === 'up');
32
  $('#tabCam').classList.toggle('active', t === 'cam');
@@ -51,7 +44,7 @@ async function startCam() {
51
  stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facing, width: { ideal: 1280 } }, audio: false });
52
  $('#video').srcObject = stream;
53
  } catch (e) {
54
- alert(T('เปิดกล้องไม่ได้ — ลองอนุญาตสิทธิ์กล้อง หรือใช้การอัปโหลดแทน', 'Cannot open camera — allow camera permission or use upload.'));
55
  setTab('up');
56
  }
57
  }
@@ -60,7 +53,7 @@ $('#flip').onclick = () => { facing = facing === 'environment' ? 'user' : 'envir
60
  $('#snap').onclick = () => {
61
  const v = $('#video'), c = $('#canvas');
62
  if (!v.videoWidth) return;
63
- const s = Math.min(v.videoWidth, v.videoHeight); // crop กลางเป็นสี่เหลี่ยม
64
  c.width = s; c.height = s;
65
  c.getContext('2d').drawImage(v, (v.videoWidth - s) / 2, (v.videoHeight - s) / 2, s, s, 0, 0, s, s);
66
  c.toBlob(b => analyze(b), 'image/jpeg', 0.92);
@@ -68,62 +61,178 @@ $('#snap').onclick = () => {
68
 
69
  // ---- analyze ----
70
  function show(el) {
71
- ['#chooser', '#upPanel', '#camPanel', '#loading', '#result'].forEach(s => $(s).style.display = 'none');
72
  if (el === '#result') $(el).style.display = 'flex';
73
  else if (el === '#loading') $(el).style.display = 'block';
74
- else { $('#chooser').style.display = 'grid'; $(el).style.display = el === '#camPanel' ? 'block' : 'block'; }
75
  }
 
76
  async function analyze(f) {
77
- stopCam(); show('#loading');
78
- const fd = new FormData(); fd.append('image', f);
79
  try {
80
  const r = await fetch('/predict', { method: 'POST', body: fd });
81
  const d = await r.json();
82
  if (d.error) throw new Error(d.error);
83
- if (d.not_fundus) renderNotFundus(d); else render(d);
84
  } catch (e) { alert(T('วิเคราะห์ไม่สำเร็จ: ', 'Failed: ') + e.message); backToChoose(); }
85
  }
86
 
87
  function setParts(on) {
88
- ['.stage-card', '.img-grid', '.why', '.disclaimer'].forEach(s => {
89
  const e = document.querySelector('#result ' + s); if (e) e.style.display = on ? '' : 'none';
90
  });
91
  }
92
 
93
- function renderNotFundus(d) {
94
  const v = $('#verdict');
95
  v.className = 'card verdict warn';
96
  v.innerHTML = `<div class="vi"><i class="ti ti-photo-x"></i></div>
97
- <div class="vt"><h2>${T('ไม่ใช่ภาพจอประสาทตา', 'Not a fundus image')}</h2>
98
  <p>${getLang() === 'en' ? d.message_en : d.message_th}</p></div>`;
99
  setParts(false);
100
  show('#result');
101
  }
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  function render(d) {
104
  setParts(true);
 
 
 
 
 
 
 
 
 
 
105
  const v = $('#verdict');
106
- v.className = 'card verdict ' + (d.referable ? 'bad' : 'ok');
107
- v.innerHTML = `<div class="vi"><i class="ti ti-${d.referable ? 'alert-triangle' : 'circle-check'}"></i></div>
108
- <div class="vt"><h2>${d.referable ? T('พบความผิดปกติ — ควรพบจักษุแพทย์', 'Abnormal — see an ophthalmologist') : T('ปกติ — ไม่พบความเสี่ยงที่ต้องส่งต่อ', 'Normal — no referral needed')}</h2>
109
- <p>${T('ระดับ', 'Level')}: <b>${d.grade_name}</b>${d.demo ? ' · ' + T('สาธิต', 'demo') : ''}</p></div>
110
  <div class="vp"><b>${d.risk_percent}%</b><span>${T('ความเสี่ยง', 'risk')}</span></div>`;
111
 
112
  const names = STAGES[getLang()];
113
  $('#stages').innerHTML = names.map((s, i) => `<div class="st ${i === d.grade ? 'on g' + i : ''}">${i === 4 ? 'Prolif.' : s}</div>`).join('');
114
  $('#scoreFill').style.width = Math.min(100, Math.max(3, d.score / 4 * 100)) + '%';
115
  $('#scoreVal').textContent = 'score ' + d.score.toFixed(2);
116
- if (d.preprocessed) $('#imgPre').src = 'data:image/png;base64,' + d.preprocessed;
117
- if (d.gradcam) { $('#imgCam').src = 'data:image/png;base64,' + d.gradcam; $('#imgCam').parentElement.style.display = 'block'; }
118
- else $('#imgCam').parentElement.style.display = 'none';
119
- $('#why').innerHTML = `<i class="ti ti-bulb"></i><div class="wt"><b>${T('AI พิจารณาอะไร', 'What the AI considered')}:</b> ${TIPS[getLang()][d.grade]} ${T('ภาพด้านบนแสดงบริเวณที่โมเดลให้ความสำคัญ', 'The image above shows where the model focused.')}</div>`;
 
 
120
  show('#result');
121
  }
122
 
123
  function backToChoose() {
124
  ['#loading', '#result', '#camPanel'].forEach(s => $(s).style.display = 'none');
125
- $('#chooser').style.display = 'grid'; $('#upPanel').style.display = 'block';
126
  $('#tabUp').classList.add('active'); $('#tabCam').classList.remove('active');
127
  }
128
  $('#again').onclick = () => { file.value = ''; backToChoose(); };
129
- $('#send').onclick = () => alert(T('ส่งผลให้จักษุแพทย์ (เชื่อมระบบโรงพยาบาลในเฟสถัดไป)', 'Sent to ophthalmologist (hospital integration in next phase)'));
 
1
  const $ = s => document.querySelector(s);
2
  const STAGES = { th: ["No DR", "Mild", "Moderate", "Severe", "Proliferative"], en: ["No DR", "Mild", "Moderate", "Severe", "Proliferative"] };
3
  const TIPS = {
4
+ th: { 0: 'ไม่พบลักษณะของเบาหวานขึ้นจอตา', 1: 'พบสัญญาณเริ่มต้น เช่น microaneurysm เล็กน้อย', 2: 'พบลักษณะระดับปานกลาง เช่น hard exudate / จุดเลือดออก', 3: 'พบความผิดปกติระดับรุนแรง ควรพบจักษุแพทย์โดยเร็ว', 4: 'พบลักษณะระยะลุกลาม ควรพบจักษุแพทย์ทันที' },
5
+ en: { 0: 'No signs of diabetic retinopathy.', 1: 'Early signs such as a few microaneurysms.', 2: 'Moderate features such as hard exudates / hemorrhages.', 3: 'Severe abnormalities. See an ophthalmologist soon.', 4: 'Proliferative features. See an ophthalmologist now.' }
 
 
 
 
 
 
 
 
 
 
 
 
6
  };
7
  const T = (th, en) => getLang() === 'en' ? en : th;
8
 
9
  fetch('/status').then(r => r.json()).then(s => { if (s.demo) $('#modeTag').style.display = 'inline-flex'; }).catch(() => {});
 
 
10
  setTimeout(() => { const s = document.getElementById('splash'); if (s) s.style.display = 'none'; }, 2500);
11
 
12
+ // ---- image source mode ----
13
+ let MODE = 'fundus';
14
+ document.querySelectorAll('.mode-opt').forEach(b => b.onclick = () => {
15
+ document.querySelectorAll('.mode-opt').forEach(x => x.classList.remove('active'));
16
+ b.classList.add('active'); MODE = b.dataset.mode;
17
+ });
18
+
19
  // ---- tabs ----
20
  let stream = null, facing = 'environment';
21
+ $('#tabUp').onclick = () => setTab('up');
22
+ $('#tabCam').onclick = () => setTab('cam');
23
  function setTab(t) {
24
  $('#tabUp').classList.toggle('active', t === 'up');
25
  $('#tabCam').classList.toggle('active', t === 'cam');
 
44
  stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facing, width: { ideal: 1280 } }, audio: false });
45
  $('#video').srcObject = stream;
46
  } catch (e) {
47
+ alert(T('เปิดกล้องไม่ได้ — ลองอนุญาตสิทธิ์กล้อง หรือใช้การอัปโหลดแทน', 'Cannot open camera — allow permission or use upload.'));
48
  setTab('up');
49
  }
50
  }
 
53
  $('#snap').onclick = () => {
54
  const v = $('#video'), c = $('#canvas');
55
  if (!v.videoWidth) return;
56
+ const s = Math.min(v.videoWidth, v.videoHeight);
57
  c.width = s; c.height = s;
58
  c.getContext('2d').drawImage(v, (v.videoWidth - s) / 2, (v.videoHeight - s) / 2, s, s, 0, 0, s, s);
59
  c.toBlob(b => analyze(b), 'image/jpeg', 0.92);
 
61
 
62
  // ---- analyze ----
63
  function show(el) {
64
+ ['#chooser', '#modeRow', '#upPanel', '#camPanel', '#loading', '#result'].forEach(s => $(s).style.display = 'none');
65
  if (el === '#result') $(el).style.display = 'flex';
66
  else if (el === '#loading') $(el).style.display = 'block';
67
+ else { $('#modeRow').style.display = 'flex'; $('#chooser').style.display = 'grid'; $(el).style.display = 'block'; }
68
  }
69
+ let lastFile = null, lastResult = null, lesionLoaded = false;
70
  async function analyze(f) {
71
+ stopCam(); show('#loading'); lastFile = f;
72
+ const fd = new FormData(); fd.append('image', f); fd.append('mode', MODE);
73
  try {
74
  const r = await fetch('/predict', { method: 'POST', body: fd });
75
  const d = await r.json();
76
  if (d.error) throw new Error(d.error);
77
+ if (d.not_gradable) renderReject(d); else render(d);
78
  } catch (e) { alert(T('วิเคราะห์ไม่สำเร็จ: ', 'Failed: ') + e.message); backToChoose(); }
79
  }
80
 
81
  function setParts(on) {
82
+ ['.result-main', '.disclaimer'].forEach(s => {
83
  const e = document.querySelector('#result ' + s); if (e) e.style.display = on ? '' : 'none';
84
  });
85
  }
86
 
87
+ function renderReject(d) {
88
  const v = $('#verdict');
89
  v.className = 'card verdict warn';
90
  v.innerHTML = `<div class="vi"><i class="ti ti-photo-x"></i></div>
91
+ <div class="vt"><h2>${T('ภาพใช้วินิจฉัยไม่ได้', 'Image not gradable')}</h2>
92
  <p>${getLang() === 'en' ? d.message_en : d.message_th}</p></div>`;
93
  setParts(false);
94
  show('#result');
95
  }
96
 
97
+ // ---- viewer state ----
98
+ let LAYERS = {}, baseSel = 'raw';
99
+ function applyOpacity() { $('#imgLesion').style.opacity = ($('#opacity').value / 100).toFixed(2); }
100
+ function setBaseMode(m) {
101
+ if (m === 'enh' && !LAYERS.enhanced) return;
102
+ baseSel = m;
103
+ $('#baseRaw').classList.toggle('on', m === 'raw');
104
+ $('#baseEnh').classList.toggle('on', m === 'enh');
105
+ $('#imgBase').src = 'data:image/png;base64,' + (m === 'enh' ? LAYERS.enhanced : LAYERS.raw);
106
+ $('#baseLbl').textContent = m === 'enh' ? T('ภาพปรับชัด (CLAHE)', 'Enhanced (CLAHE)') : T('ภาพต้นฉบับ (Raw)', 'Original (Raw)');
107
+ }
108
+ function toggleLayer(btn, img) {
109
+ if (btn.classList.contains('disabled')) return;
110
+ const on = btn.classList.toggle('on');
111
+ img.style.visibility = on ? 'visible' : 'hidden';
112
+ }
113
+ $('#tgLesion').onclick = () => toggleLayer($('#tgLesion'), $('#imgLesion'));
114
+ $('#tgLandmark').onclick = () => toggleLayer($('#tgLandmark'), $('#imgLandmark'));
115
+ $('#baseRaw').onclick = () => setBaseMode('raw');
116
+ $('#baseEnh').onclick = () => setBaseMode('enh');
117
+ $('#opacity').oninput = applyOpacity;
118
+
119
+ function setupViewer(d) {
120
+ LAYERS = d.layers || {}; // มีแค่ raw ตอนแรก — lesion โหลดทีหลังผ่าน /explain
121
+ const les = $('#imgLesion'), lm = $('#imgLandmark');
122
+ setBaseMode('raw');
123
+ les.style.display = 'none'; les.style.visibility = 'hidden';
124
+ lm.style.display = 'none'; lm.style.visibility = 'hidden';
125
+ $('#tgLesion').classList.add('disabled'); $('#tgLesion').classList.remove('on');
126
+ $('#tgLandmark').classList.add('disabled'); $('#tgLandmark').classList.remove('on');
127
+ $('#baseEnh').classList.add('disabled');
128
+ $('#opacity').parentElement.style.display = 'none';
129
+ applyOpacity();
130
+ }
131
+
132
+ async function loadExplain() {
133
+ lesionLoaded = true; // กันยิงซ้ำ
134
+ $('#findings').innerHTML = `<div class="lesion-loading"><i class="ti ti-loader-2 spin"></i> ${T('กำลังวิเคราะห์รอยโรค…', 'Analyzing lesions…')}</div>`;
135
+ try {
136
+ const fd = new FormData(); fd.append('image', lastFile); fd.append('mode', MODE);
137
+ fd.append('grade_name', (lastResult && lastResult.grade_name) || '');
138
+ const ex = await fetch('/explain', { method: 'POST', body: fd }).then(r => r.json());
139
+ if (ex.error || ex.lesion_unavailable) {
140
+ $('#findings').innerHTML = `<div class="frow"><span class="fl">${T('รอยโรค', 'Lesions')}</span><span class="fv" style="font-weight:400">${T('วิเคราะห์ไม่ได้', 'unavailable')}</span></div>`;
141
+ return;
142
+ }
143
+ LAYERS.lesion = ex.layers.lesion; LAYERS.landmark = ex.layers.landmark; LAYERS.enhanced = ex.layers.enhanced;
144
+ const les = $('#imgLesion'), lm = $('#imgLandmark');
145
+ les.src = 'data:image/png;base64,' + ex.layers.lesion; les.style.display = '';
146
+ lm.src = 'data:image/png;base64,' + ex.layers.landmark; lm.style.display = '';
147
+ $('#tgLesion').classList.remove('disabled'); $('#tgLesion').classList.add('on');
148
+ $('#tgLandmark').classList.remove('disabled'); $('#tgLandmark').classList.add('on');
149
+ $('#baseEnh').classList.remove('disabled');
150
+ $('#opacity').parentElement.style.display = '';
151
+ $('#imgLesion').style.visibility = 'visible'; $('#imgLandmark').style.visibility = 'visible';
152
+ applyOpacity();
153
+ renderFindings(ex);
154
+ $('#why').innerHTML = `<i class="ti ti-bulb"></i><div class="wt"><b>${T('เหตุผลจาก AI', 'AI rationale')}:</b> ${ex.rationale}</div>`;
155
+ } catch (e) {
156
+ $('#findings').innerHTML = `<div class="frow"><span class="fl">error</span><span class="fv" style="font-weight:400">${e.message}</span></div>`;
157
+ }
158
+ }
159
+
160
+ let deepOpened = false;
161
+ $('#deepBtn').onclick = async () => {
162
+ const dd = $('#deepdive'), open = dd.style.display === 'none';
163
+ dd.style.display = open ? 'block' : 'none';
164
+ $('#deepBtn').classList.toggle('open', open);
165
+ if (open) {
166
+ if (lastResult && lastResult.lesion_available && !lesionLoaded && lastFile) await loadExplain();
167
+ $('#imgLesion').style.visibility = $('#tgLesion').classList.contains('on') ? 'visible' : 'hidden';
168
+ $('#imgLandmark').style.visibility = $('#tgLandmark').classList.contains('on') ? 'visible' : 'hidden';
169
+ applyOpacity();
170
+ dd.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
171
+ } else { // collapse → clean screener image
172
+ $('#imgLesion').style.visibility = 'hidden';
173
+ $('#imgLandmark').style.visibility = 'hidden';
174
+ }
175
+ };
176
+
177
+ function renderFindings(d) {
178
+ const f = d.features, fov = d.fovea_metrics;
179
+ if (!f) {
180
+ const msg = (lastResult && lastResult.lesion_available)
181
+ ? T('เปิดส่วนนี้เพื่อให้ AI วิเคราะห์รอยโรค', 'AI analyzes lesions on open')
182
+ : T('การวิเคราะห์รอยโรคไม่พร้อมใช้งาน', 'lesion analysis unavailable');
183
+ $('#findings').innerHTML = `<div class="frow"><span class="fl">${T('รอยโรค', 'Lesions')}</span><span class="fv" style="font-weight:400;color:var(--text-3)">${msg}</span></div>`;
184
+ return;
185
+ }
186
+ const exdd = (fov && fov.EX && fov.EX.min_dd != null) ? fov.EX.min_dd : null;
187
+ const exWarn = exdd != null && exdd <= 1.0;
188
+ const rows = [
189
+ ['Microaneurysm', `~${f.MA.count} ${T('จุด', 'spots')}`, ''],
190
+ ['Hemorrhage', `${f.HE.count} ${T('ก้อน', 'blobs')} · ${f.HE.area_pct}%`, ''],
191
+ ['Hard exudate', `${f.EX.area_pct}%${exdd != null ? ` · ${exdd} DD` : ''}`, exWarn ? 'warn' : ''],
192
+ ['Soft exudate', f.SE.area_px > 0 ? T('พบ', 'present') : T('ไม่พบ', 'none'), '']
193
+ ];
194
+ let html = rows.map(r => `<div class="frow"><span class="fl">${r[0]}</span><span class="fv ${r[2]}">${r[1]}</span></div>`).join('');
195
+ if (exWarn) html += `<div class="warnbox"><i class="ti ti-alert-circle"></i> ${T('EX ภายใน 1 DD จาก fovea — เสี่ยง CSME', 'EX within 1 DD of fovea — CSME risk')}</div>`;
196
+ $('#findings').innerHTML = html;
197
+ }
198
+
199
+ const CONF = { normal: { th: 'สูง', en: 'high' }, review: { th: 'ปานกลาง', en: 'medium' }, refer: { th: 'สูง', en: 'high' } };
200
  function render(d) {
201
  setParts(true);
202
+ lastResult = d; lesionLoaded = false;
203
+ $('#deepdive').style.display = 'none'; $('#deepBtn').classList.remove('open'); deepOpened = false;
204
+ // binary action สำหรับคนคัดกรอง: review รวมเข้า "ควรพบแพทย์" (ไม่มั่นใจ = ให้หมอดู, ทิศปลอดภัย)
205
+ const needDoc = d.zone !== 'normal';
206
+ const zc = needDoc ? (d.zone === 'refer' ? 'bad' : 'warn') : 'ok';
207
+ const zi = needDoc ? (d.zone === 'refer' ? 'alert-triangle' : 'alert-circle') : 'circle-check';
208
+ const title = needDoc
209
+ ? (d.grade >= 3 ? T('ควรพบจักษุแพทย์โดยเร็ว', 'See an ophthalmologist soon') : T('ควรพบจักษุแพทย์', 'See an ophthalmologist'))
210
+ : T('ไม่ต้องส่งต่อ', 'No referral needed');
211
+ const conf = getLang() === 'en' ? CONF[d.zone].en : CONF[d.zone].th;
212
  const v = $('#verdict');
213
+ v.className = 'card verdict ' + zc;
214
+ v.innerHTML = `<div class="vi"><i class="ti ti-${zi}"></i></div>
215
+ <div class="vt"><h2>${title}</h2>
216
+ <p>${T('ผลคัดกรอง', 'Result')}: <b>${d.grade_name}</b> · ${T('ความมั่นใจ', 'confidence')} ${conf}${d.demo ? ' · ' + T('สาธิต', 'demo') : ''}</p></div>
217
  <div class="vp"><b>${d.risk_percent}%</b><span>${T('ความเสี่ยง', 'risk')}</span></div>`;
218
 
219
  const names = STAGES[getLang()];
220
  $('#stages').innerHTML = names.map((s, i) => `<div class="st ${i === d.grade ? 'on g' + i : ''}">${i === 4 ? 'Prolif.' : s}</div>`).join('');
221
  $('#scoreFill').style.width = Math.min(100, Math.max(3, d.score / 4 * 100)) + '%';
222
  $('#scoreVal').textContent = 'score ' + d.score.toFixed(2);
223
+
224
+ setupViewer(d);
225
+ renderFindings(d);
226
+ $('#why').innerHTML = d.rationale
227
+ ? `<i class="ti ti-bulb"></i><div class="wt"><b>${T('เหตุผลจาก AI', 'AI rationale')}:</b> ${d.rationale}</div>`
228
+ : `<i class="ti ti-bulb"></i><div class="wt">${TIPS[getLang()][d.grade]}</div>`;
229
  show('#result');
230
  }
231
 
232
  function backToChoose() {
233
  ['#loading', '#result', '#camPanel'].forEach(s => $(s).style.display = 'none');
234
+ $('#modeRow').style.display = 'flex'; $('#chooser').style.display = 'grid'; $('#upPanel').style.display = 'block';
235
  $('#tabUp').classList.add('active'); $('#tabCam').classList.remove('active');
236
  }
237
  $('#again').onclick = () => { file.value = ''; backToChoose(); };
238
+ $('#send').onclick = () => alert(T('ส่งผลให้จักษุแพทย์ (เชื่อมระบบโรงพยาบาลในเฟสถัดไป)', 'Sent to ophthalmologist (hospital integration next phase)'));
history.json CHANGED
@@ -1 +1 @@
1
- [{"time": "2026-06-13T20:53:54", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 16.2}, {"time": "2026-06-13T20:53:46", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 32.0}, {"time": "2026-06-13T20:53:38", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 10.3}, {"time": "2026-06-13T20:53:25", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 85.0}, {"time": "2026-06-13T20:53:16", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 60.7}, {"time": "2026-06-13T20:53:04", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 6.4}, {"time": "2026-06-13T20:52:52", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:52:44", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:52:36", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 84.6}, {"time": "2026-06-13T20:52:26", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 98.1}, {"time": "2026-06-13T20:52:16", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 98.3}, {"time": "2026-06-13T20:52:07", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 97.6}, {"time": "2026-06-13T20:46:38", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 8.6}, {"time": "2026-06-13T20:45:48", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 79.0}, {"time": "2026-06-13T20:44:50", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:44:18", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.8}, {"time": "2026-06-13T20:43:10", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 97.4}, {"time": "2026-06-13T19:36:38", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T19:28:34", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T15:50:28", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:49:43", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:49:29", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 6.5}, {"time": "2026-06-13T14:48:43", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 48.9}, {"time": "2026-06-13T14:39:30", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:24:56", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 76.2}]
 
1
+ [{"time": "2026-06-23T20:08:42", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T20:08:04", "grade": 2, "grade_name": "Moderate", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T20:07:44", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T20:07:41", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T17:51:55", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 31.4}, {"time": "2026-06-23T07:19:46", "grade": 1, "grade_name": "Mild", "zone": "review", "referable": false, "risk_percent": 64.9}, {"time": "2026-06-23T07:18:26", "grade": 2, "grade_name": "Moderate", "zone": "refer", "referable": true, "risk_percent": 93.6}, {"time": "2026-06-23T07:17:42", "grade": 3, "grade_name": "Severe", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T07:17:20", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 5.7}, {"time": "2026-06-23T07:17:10", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 5.7}, {"time": "2026-06-23T07:15:27", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T07:15:13", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T07:09:34", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 2.9}, {"time": "2026-06-23T07:08:56", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 22.3}, {"time": "2026-06-23T07:08:45", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 31.4}, {"time": "2026-06-23T07:07:22", "grade": 3, "grade_name": "Severe", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T07:05:59", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 2.9}, {"time": "2026-06-23T07:05:12", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 31.4}, {"time": "2026-06-23T07:04:35", "grade": 4, "grade_name": "Proliferative", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T07:04:05", "grade": 4, "grade_name": "Proliferative", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T07:02:01", "grade": 1, "grade_name": "Mild", "zone": "refer", "referable": true, "risk_percent": 50.0}, {"time": "2026-06-23T07:01:29", "grade": 0, "grade_name": "No DR", "zone": "review", "referable": false, "risk_percent": 31.4}, {"time": "2026-06-23T07:00:39", "grade": 2, "grade_name": "Moderate", "zone": "refer", "referable": true, "risk_percent": 99.6}, {"time": "2026-06-23T07:00:07", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T06:59:18", "grade": 1, "grade_name": "Mild", "zone": "refer", "referable": true, "risk_percent": 50.0}, {"time": "2026-06-23T06:36:29", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T06:33:15", "grade": 0, "grade_name": "No DR", "zone": "normal", "referable": false, "risk_percent": 2.5}, {"time": "2026-06-23T06:26:19", "grade": 1, "grade_name": "Mild", "zone": "refer", "referable": true, "risk_percent": 64.9}, {"time": "2026-06-23T03:36:48", "grade": 1, "grade_name": "Mild", "zone": "refer", "referable": true, "risk_percent": 64.9}, {"time": "2026-06-13T20:53:54", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 16.2}, {"time": "2026-06-13T20:53:46", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 32.0}, {"time": "2026-06-13T20:53:38", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 10.3}, {"time": "2026-06-13T20:53:25", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 85.0}, {"time": "2026-06-13T20:53:16", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 60.7}, {"time": "2026-06-13T20:53:04", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 6.4}, {"time": "2026-06-13T20:52:52", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:52:44", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:52:36", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 84.6}, {"time": "2026-06-13T20:52:26", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 98.1}, {"time": "2026-06-13T20:52:16", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 98.3}, {"time": "2026-06-13T20:52:07", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 97.6}, {"time": "2026-06-13T20:46:38", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 8.6}, {"time": "2026-06-13T20:45:48", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 79.0}, {"time": "2026-06-13T20:44:50", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.7}, {"time": "2026-06-13T20:44:18", "grade": 4, "grade_name": "Proliferative", "referable": true, "risk_percent": 99.8}, {"time": "2026-06-13T20:43:10", "grade": 3, "grade_name": "Severe", "referable": true, "risk_percent": 97.4}, {"time": "2026-06-13T19:36:38", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T19:28:34", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T15:50:28", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:49:43", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:49:29", "grade": 0, "grade_name": "No DR", "referable": false, "risk_percent": 6.5}, {"time": "2026-06-13T14:48:43", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 48.9}, {"time": "2026-06-13T14:39:30", "grade": 1, "grade_name": "Mild", "referable": false, "risk_percent": 20.2}, {"time": "2026-06-13T14:24:56", "grade": 2, "grade_name": "Moderate", "referable": true, "risk_percent": 76.2}]
models/quality_gate.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17c912f694b51e6d9ec975fed2bea3ddc431c59787aafc003ac7fae83bd7ed85
3
+ size 16341973
models/unet_lesion_v2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77042b20ed7e3a6c6b3f0d14e591ce96aa63741633445ea399f4b25c33fdf435
3
+ size 84078343
requirements.txt CHANGED
@@ -6,4 +6,6 @@ opencv-python-headless==4.10.0.84
6
  torch==2.2.2
7
  torchvision==0.17.2
8
  timm==1.0.7
9
- grad-cam==1.5.0
 
 
 
6
  torch==2.2.2
7
  torchvision==0.17.2
8
  timm==1.0.7
9
+ segmentation-models-pytorch==0.5.0
10
+ scikit-learn==1.6.1
11
+ joblib==1.4.2