Download app.py from Bora9/paly: direct link, hf CLI and curl.
- Browser
- Download file 53 kB
-
https://huggingface.co/spaces/Bora9/paly/resolve/main/app.py
- Command line
-
hf download hf://spaces/Bora9/paly/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Bora9/paly/resolve/main/app.py
53 kB
| import os | |
| import re | |
| import json | |
| import tempfile | |
| import warnings | |
| from pathlib import Path | |
| from collections import defaultdict | |
| from datetime import datetime | |
| import numpy as np | |
| import pandas as pd | |
| import cv2 | |
| import matplotlib | |
| matplotlib.use("Agg") # Headless mode for Hugging Face/Servers | |
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as mpatches | |
| import matplotlib.colors as mcolors | |
| from matplotlib.patches import Polygon | |
| import gradio as gr | |
| from ultralytics import YOLO | |
| warnings.filterwarnings("ignore") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 1. SETTINGS & CONFIGURATION | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CLASS_NAMES = ["AOM", "Background", "Palynomorph", "Phytoclast"] | |
| PALYNO_GROUPS = ["AOM", "Palynomorph", "Phytoclast"] | |
| BG_CLASS = "Background" | |
| IOU_THRESH = 0.45 | |
| CALIBRATION = { | |
| 10: {"um_per_pixel": 1.2403}, | |
| 20: {"um_per_pixel": 0.6202}, | |
| 40: {"um_per_pixel": 0.3101}, | |
| } | |
| COLORS = { | |
| "AOM" : "#C0392B", | |
| "Palynomorph": "#27AE60", | |
| "Phytoclast" : "#2980B9", | |
| } | |
| MEAN_COLOR = "#E91E63" | |
| TYSON_FIELDS = [ | |
| {"num": "I", "name": "Highly proximal shelf or basin", "color": "#C8E6C9", "pts": [(0,0,100),(10,0,90),(0,10,90)]}, | |
| {"num": "II", "name": "Marginal dysoxic-oxic shelf", "color": "#BBDEFB", "pts": [(10,0,90),(40,0,60),(40,10,50),(0,50,50),(0,10,90)]}, | |
| {"num": "III", "name": "Heterolithic oxic shelf (proximal)", "color": "#C8E6C9", "pts": [(0,50,50),(30,50,20),(0,80,20)]}, | |
| {"num": "IVa", "name": "Shelf to basin transition (a)", "color": "#FFF9C4", "pts": [(40,10,50),(0,50,50),(10,50,40),(40,20,40)]}, | |
| {"num": "IVb", "name": "Shelf to basin transition (b)", "color": "#FFE0B2", "pts": [(40,20,40),(10,50,40),(30,50,20),(40,40,20)]}, | |
| {"num": "V", "name": "Mud-dominated oxic shelf (distal)", "color": "#BBDEFB", "pts": [(30,50,20),(50,50,0),(0,100,0),(0,80,20)]}, | |
| {"num": "VI", "name": "Proximal suboxic-anoxic shelf", "color": "#FFE0B2", "pts": [(40,0,60),(40,10,50),(40,20,40),(60,0,40)]}, | |
| {"num": "VII", "name": "Distal dysoxic-anoxic shelf", "color": "#FFCDD2", "pts": [(40,40,20),(60,40,0),(50,50,0),(30,50,20)]}, | |
| {"num": "VIII", "name": "Distal dysoxic-anoxic basin", "color": "#E1BEE7", "pts": [(60,0,40),(80,0,20),(80,20,0),(60,40,0),(40,40,20),(40,20,40)]}, | |
| {"num": "IX", "name": "Distal suboxic-anoxic basin", "color": "#FFCDD2", "pts": [(80,0,20),(80,20,0),(100,0,0)]}, | |
| ] | |
| _PX = {"aom": (76, 530), "pal": (660, 530), "phy": (368, 105)} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 2. MODEL LOADING | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODEL_PATH = "best.pt" | |
| if os.path.exists(MODEL_PATH): | |
| model = YOLO(MODEL_PATH) | |
| else: | |
| model = None | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 3. MATH HELPER FUNCTIONS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def tc(aom, pal, phy): | |
| total = aom + pal + phy | |
| if total == 0: | |
| return 368.0, 317.0 | |
| a, p, h = aom / total, pal / total, phy / total | |
| px = a * _PX["aom"][0] + p * _PX["pal"][0] + h * _PX["phy"][0] | |
| py = a * _PX["aom"][1] + p * _PX["pal"][1] + h * _PX["phy"][1] | |
| return px, py | |
| def pixels_to_um2(px: float, mag: int) -> float: | |
| cal = CALIBRATION.get(mag, CALIBRATION[10]) | |
| return px * (cal["um_per_pixel"] ** 2) | |
| def classify_facies(aom_pct, pal_pct, phy_pct): | |
| best_field, best_name, min_dist = "IVa", "Shelf to basin transition (a)", float("inf") | |
| for field in TYSON_FIELDS: | |
| pts = field["pts"] | |
| c_aom = sum(p[0] for p in pts) / len(pts) | |
| c_pal = sum(p[1] for p in pts) / len(pts) | |
| c_phy = sum(p[2] for p in pts) / len(pts) | |
| dist = ((aom_pct - c_aom)**2 + (pal_pct - c_pal)**2 + (phy_pct - c_phy)**2)**0.5 | |
| if dist < min_dist: | |
| min_dist, best_field, best_name = dist, field["num"], field["name"] | |
| return best_field, best_name | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 3b. COLOR NORMALIZATION & TAI (flat-field + white point + optical density) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Why not raw HSV? Raw HSV (especially V and S) depends directly on lamp intensity, | |
| # camera exposure, white balance and vignetting, so the same palynomorph gives a | |
| # different "V" on a different microscope. Instead: | |
| # 1) The illumination field I0(x,y) is estimated from the background (pixels that | |
| # are not objects) with a vignette polynomial plus a local residual. | |
| # -> flat-field, white balance and exposure are corrected in one step. | |
| # 2) Color is converted to Optical Density in linear (gamma-free) space: | |
| # OD = -log10( I / I0 ) (BeerβLambert) | |
| # so the measurement depends on how much light the material absorbs, | |
| # not on how much light the lamp emits. | |
| # 3) TAI is read from an OD(Y) -> TAI calibration curve (monotone, piecewise linear). | |
| # The default curve uses approximate values; you can calibrate it with your own | |
| # reference samples (π― TAI Calibration tab). | |
| MODE_FLAT = "Auto flat-field + white balance (recommended)" | |
| MODE_GLOBAL = "Auto global white balance + exposure" | |
| MODE_OFF = "Off (raw colors)" | |
| NORM_MODES = [MODE_FLAT, MODE_GLOBAL, MODE_OFF] | |
| FEED_BGR_TO_MODEL = True # Ultralytics numpy girdisini BGR bekler (bkz. _to_model_input) | |
| CALIB_REPO_PATH = "tai_calibration.json" # if committed to the repo it becomes the default for everyone | |
| TARGET_WHITE_SRGB = 235 # background level in the normalized image (0-255) | |
| LUMA = np.array([0.2126, 0.7152, 0.0722], dtype=np.float32) | |
| _c = np.arange(256, dtype=np.float32) / 255.0 | |
| SRGB2LIN = np.where(_c <= 0.04045, _c / 12.92, ((_c + 0.055) / 1.055) ** 2.4).astype(np.float32) | |
| WHITE_LIN = float(SRGB2LIN[TARGET_WHITE_SRGB]) | |
| # Default OD(Y) -> TAI anchor points. WARNING: uncalibrated starting values. | |
| DEFAULT_ANCHORS = [(0.03, 1.0), (0.10, 1.5), (0.20, 2.0), (0.35, 2.5), (0.55, 3.0), | |
| (0.80, 3.5), (1.10, 4.0), (1.50, 4.5), (2.00, 5.0)] | |
| def linear_to_srgb(x): | |
| c = np.clip(x, 0.0, 1.0).astype(np.float32) | |
| return np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(c, 1 / 2.4) - 0.055) | |
| def _to_model_input(img_rgb): | |
| """Ultralytics treats numpy arrays as BGR (cv2.imread channel order).""" | |
| return np.ascontiguousarray(img_rgb[..., ::-1]) if FEED_BGR_TO_MODEL else img_rgb | |
| def _file_path(f): | |
| if f is None: return None | |
| if isinstance(f, str): return f | |
| if isinstance(f, dict): return f.get("name") or f.get("path") | |
| return getattr(f, "name", None) | |
| def maturity_label(tai): | |
| if tai >= 3.7: return "Overmature (Dry Gas)" | |
| if tai >= 3.0: return "Late Mature (Wet Gas)" | |
| if tai >= 2.5: return "Mature (Oil Window)" | |
| if tai >= 2.0: return "Early Mature" | |
| if tai >= 1.5: return "ImmatureβEarly Mature" | |
| return "Immature" | |
| # ββ Calibration loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_calib(f=None): | |
| """Order: uploaded JSON -> tai_calibration.json in the repo -> built-in default.""" | |
| note = "" | |
| cands = [] | |
| up = _file_path(f) | |
| if up: cands.append((up, "uploaded calibration file")) | |
| if os.path.exists(CALIB_REPO_PATH): cands.append((CALIB_REPO_PATH, f"{CALIB_REPO_PATH} (repo)")) | |
| for path, label in cands: | |
| try: | |
| with open(path, encoding="utf-8") as fh: | |
| d = json.load(fh) | |
| anc = sorted((float(a), float(b)) for a, b in d["anchors"]) | |
| if len(anc) >= 2: | |
| return {"x": [a for a, _ in anc], "y": [b for _, b in anc], "source": label, | |
| "norm_mode": d.get("norm_mode"), "calibrated": True, "note": note} | |
| except Exception as e: | |
| note = f"Calibration file could not be read ({e}); default curve used." | |
| return {"x": [a for a, _ in DEFAULT_ANCHORS], "y": [b for _, b in DEFAULT_ANCHORS], | |
| "source": "built-in default (NOT calibrated)", "norm_mode": None, | |
| "calibrated": False, "note": note} | |
| # ββ Illumination field estimation ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _smooth_field(small, gate, sigma, glob): | |
| m = gate.astype(np.float32) | |
| num = cv2.GaussianBlur(small * m[..., None], (0, 0), sigma) | |
| den = cv2.GaussianBlur(m, (0, 0), sigma) | |
| eps = 0.02 # fall back softly to the glob value where there is no data | |
| return (num + eps * glob) / (den[..., None] + eps) | |
| def _fit_vignette(small, valid): | |
| """Fits log(I) ~ [1, x, y, xΒ², xy, yΒ², rβ΄] per channel, iteratively rejecting | |
| dark outlier pixels (undetected debris). | |
| The parametric model extrapolates safely into corners covered by objects.""" | |
| hs, ws = small.shape[:2] | |
| yy, xx = np.mgrid[0:hs, 0:ws].astype(np.float64) | |
| x, y = xx / (ws - 1) * 2 - 1, yy / (hs - 1) * 2 - 1 | |
| r2 = x * x + y * y | |
| B = np.stack([np.ones_like(x), x, y, x * x, x * y, y * y, r2 * r2], -1).reshape(-1, 7) | |
| logI = np.log(np.maximum(small.astype(np.float64), 1e-4)).reshape(-1, 3) | |
| g = valid.reshape(-1) | |
| coef = np.zeros((7, 3)) | |
| final = g.copy() | |
| for c in range(3): | |
| coef[0, c] = np.median(logI[g, c]) if g.any() else np.log(0.8) | |
| wm = g.copy() | |
| for thr in (0.30, 0.18, 0.12, 0.09): # successively tighter dark-outlier thresholds | |
| if wm.sum() < 50: break | |
| coef[:, c] = np.linalg.lstsq(B[wm], logI[wm, c], rcond=None)[0] | |
| res = logI[:, c] - B @ coef[:, c] | |
| wm = g & (res > -thr) & (res < 0.12) | |
| final &= wm if wm.sum() >= 50 else g | |
| field = np.exp(B @ coef).reshape(hs, ws, 3).astype(np.float32) | |
| return field, final.reshape(hs, ws) | |
| def estimate_illumination(lin, exclude, mode, blank_rgb=None): | |
| """Returns I0 ((h,w,3) or (1,1,3) linear illumination field) and an info dict.""" | |
| h, w = lin.shape[:2] | |
| info = {"method": mode, "warnings": [], "white_srgb": (255, 255, 255), | |
| "bg_frac": None, "nonuni": None} | |
| if mode == MODE_OFF: | |
| return np.ones((1, 1, 3), np.float32), info | |
| s = max(1, max(h, w) // 400) | |
| hs, ws = max(8, h // s), max(8, w // s) | |
| small = cv2.resize(lin, (ws, hs), interpolation=cv2.INTER_AREA) | |
| ex = cv2.resize(exclude * 255, (ws, hs), interpolation=cv2.INTER_AREA) > 10 | |
| valid = ~ex | |
| if valid.sum() < 0.005 * valid.size: | |
| valid = np.ones_like(valid) | |
| info["warnings"].append("Almost no object-free area; illuminant estimated from the whole image (less reliable).") | |
| poly, gate = _fit_vignette(small, valid) # 1) vignette / white field | |
| sigma = max(3.0, 0.15 * min(hs, ws)) | |
| resid = _smooth_field(small / np.maximum(poly, 1e-4), gate, sigma, np.ones(3, np.float32)) | |
| field = np.maximum(poly * resid, 1e-3) # 2) local residual correction | |
| glob = np.median(small[gate], axis=0) if gate.sum() >= 20 else np.median(small[valid], axis=0) | |
| info["bg_frac"] = float(gate.mean()) | |
| info["white_srgb"] = tuple(int(round(v * 255)) for v in linear_to_srgb(glob)) | |
| if info["bg_frac"] < 0.01: | |
| info["warnings"].append("Very few background pixels were usable; white point may be inaccurate.") | |
| if float((small.max(axis=2) > 0.97).mean()) > 0.05: | |
| info["warnings"].append("More than 5% of pixels are clipped (overexposed); optical density is underestimated there.") | |
| if float(linear_to_srgb(np.array([glob @ LUMA]))[0]) * 255 < 110: | |
| info["warnings"].append("Background is dark (underexposed); increase exposure for reliable TAI.") | |
| i0 = None | |
| if blank_rgb is not None: | |
| b = cv2.resize(np.ascontiguousarray(blank_rgb[..., :3]), (w, h), interpolation=cv2.INTER_AREA) | |
| bl = cv2.GaussianBlur(SRGB2LIN[b], (0, 0), max(h, w) / 150.0) | |
| ratio = float(bl.reshape(-1, 3).mean(0) @ LUMA) / max(float(glob @ LUMA), 1e-6) | |
| if 0.8 <= ratio <= 1.25: | |
| i0 = np.maximum(bl, 1e-3) | |
| info["method"] = "Blank-slide reference image (flat-field)" | |
| else: | |
| info["warnings"].append("Blank reference brightness differs >20% from the sample background " | |
| "(different exposure/lamp?) β ignored, auto flat-field used.") | |
| if i0 is None: | |
| if mode == MODE_GLOBAL: | |
| i0 = glob.reshape(1, 1, 3).astype(np.float32) | |
| else: | |
| i0 = cv2.resize(field, (w, h), interpolation=cv2.INTER_LINEAR).astype(np.float32) | |
| if i0.shape[0] > 1: | |
| l = i0[::max(1, h // 200), ::max(1, w // 200)] @ LUMA | |
| info["nonuni"] = float((np.percentile(l, 95) - np.percentile(l, 5)) / max(float(l.mean()), 1e-6)) | |
| else: | |
| info["nonuni"] = 0.0 | |
| return i0, info | |
| def build_prep(img_rgb, result, norm_mode, blank_rgb=None): | |
| """Called once per image: linear image, I0 field, normalized RGB.""" | |
| h, w = img_rgb.shape[:2] | |
| exclude = np.zeros((h, w), np.uint8) | |
| if result is not None and result.masks is not None: | |
| for poly, c in zip(result.masks.xy, result.boxes.cls): | |
| if CLASS_NAMES[int(c)] in PALYNO_GROUPS and len(poly) >= 3: | |
| cv2.fillPoly(exclude, [np.round(poly).astype(np.int32)], 1) | |
| k = max(3, int(round(0.004 * max(h, w)))) | 1 | |
| exclude = cv2.dilate(exclude, np.ones((k, k), np.uint8)) | |
| lin = SRGB2LIN[img_rgb] | |
| i0, info = estimate_illumination(lin, exclude, norm_mode, blank_rgb) | |
| if norm_mode == MODE_OFF: | |
| norm_rgb = img_rgb | |
| else: | |
| ratio = np.clip(lin / i0, 0.0, 1.0) | |
| norm_rgb = (linear_to_srgb(ratio * WHITE_LIN) * 255 + 0.5).astype(np.uint8) | |
| return {"h": h, "w": w, "lin": lin, "i0": i0, "norm_rgb": norm_rgb, "info": info, "mode": norm_mode} | |
| # ββ Mask / measurement βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def rasterize_roi(poly, h, w): | |
| """Rasterizes a YOLO polygon at ORIGINAL resolution, only within its bounding box. | |
| (masks.data is letterboxed, so resizing it directly can shift the mask.)""" | |
| if poly is None or len(poly) < 3: return None | |
| x1 = max(0, int(np.floor(poly[:, 0].min()))); y1 = max(0, int(np.floor(poly[:, 1].min()))) | |
| x2 = min(w, int(np.ceil(poly[:, 0].max())) + 1); y2 = min(h, int(np.ceil(poly[:, 1].max())) + 1) | |
| if x2 <= x1 or y2 <= y1: return None | |
| canvas = np.zeros((y2 - y1, x2 - x1), np.uint8) | |
| pts = np.round(poly - np.array([x1, y1])).astype(np.int32) | |
| cv2.fillPoly(canvas, [pts], 1) | |
| return (x1, y1, x2, y2), canvas | |
| def measure_palynomorph(prep, roi, mask, calib): | |
| """OD-based color features and TAI for a single palynomorph.""" | |
| x1, y1, x2, y2 = roi | |
| if int(mask.sum()) < 50: return None | |
| r = np.sqrt(mask.sum() / np.pi) | |
| k = int(max(1, round(0.15 * r))) # drop edge / halo pixels | |
| core = cv2.erode(mask, np.ones((2 * k + 1, 2 * k + 1), np.uint8)) | |
| if core.sum() < 50: core = mask | |
| sel = core.astype(bool) | |
| lin = prep["lin"][y1:y2, x1:x2][sel] | |
| i0 = prep["i0"] | |
| i0 = i0.reshape(1, 3) if i0.shape[0] == 1 else i0[y1:y2, x1:x2][sel] | |
| T = np.clip(lin / np.maximum(i0, 1e-4), 1e-4, 1.0) # transmittance | |
| ypix = T @ LUMA | |
| lo, hi = np.percentile(ypix, [10, 90]) # trim folds / overlap extremes | |
| keep = (ypix >= lo) & (ypix <= hi) | |
| if keep.sum() < 20: keep = np.ones_like(keep) | |
| Tm = np.median(T[keep], axis=0) | |
| od_rgb = -np.log10(Tm) | |
| od_y = float(-np.log10(max(float(Tm @ LUMA), 1e-4))) | |
| rgb_n = (linear_to_srgb(Tm * WHITE_LIN) * 255).astype(np.uint8).reshape(1, 1, 3) | |
| lab = cv2.cvtColor(rgb_n, cv2.COLOR_RGB2LAB)[0, 0].astype(np.float32) | |
| L, a, b = lab[0] * 100 / 255, lab[1] - 128, lab[2] - 128 | |
| return {"tai": float(np.interp(od_y, calib["x"], calib["y"])), "od_y": od_y, | |
| "od_r": float(od_rgb[0]), "od_g": float(od_rgb[1]), "od_b": float(od_rgb[2]), | |
| "L": float(L), "a": float(a), "b": float(b), | |
| "hue": float(np.degrees(np.arctan2(b, a)) % 360), "n_pix": int(keep.sum())} | |
| def make_qc_image(raw_rgb, norm_rgb, max_h=500): | |
| def fit(im): | |
| s = max_h / im.shape[0] | |
| return cv2.resize(im, (max(1, int(im.shape[1] * s)), max_h), interpolation=cv2.INTER_AREA) | |
| a, b = fit(raw_rgb), fit(norm_rgb) | |
| for im, text in ((a, "RAW"), (b, "NORMALIZED")): | |
| cv2.putText(im, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 4, cv2.LINE_AA) | |
| cv2.putText(im, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA) | |
| return np.hstack([a, np.full((max_h, 8, 3), 255, np.uint8), b]) | |
| # ββ Isotonic (monotone) regression for calibration, pure numpy βββββββββββββββββ | |
| def isotonic_fit(x, y): | |
| order = np.argsort(x) | |
| xs, ys = np.asarray(x, float)[order], np.asarray(y, float)[order] | |
| vals, wts, xb = [], [], [] | |
| for xi, yi in zip(xs, ys): | |
| vals.append(yi); wts.append(1.0); xb.append(xi) | |
| while len(vals) > 1 and vals[-2] > vals[-1]: | |
| wt = wts[-2] + wts[-1] | |
| v = (vals[-2] * wts[-2] + vals[-1] * wts[-1]) / wt | |
| xm = (xb[-2] * wts[-2] + xb[-1] * wts[-1]) / wt | |
| vals[-2:], wts[-2:], xb[-2:] = [v], [wt], [xm] | |
| return np.array(xb), np.array(vals) | |
| def make_collage(crops, target_h=100, max_w=800): | |
| if not crops: return None | |
| rows = [] | |
| current_row = [] | |
| current_w = 0 | |
| for crop in crops: | |
| h, w = crop.shape[:2] | |
| if h == 0 or w == 0: continue | |
| aspect = w / h | |
| new_w = int(target_h * aspect) | |
| if new_w <= 0: continue | |
| resized = cv2.resize(crop, (new_w, target_h)) | |
| if current_w + new_w > max_w and current_row: | |
| rows.append(np.hstack(current_row)) | |
| current_row = [resized] | |
| current_w = new_w | |
| else: | |
| current_row.append(resized) | |
| current_w += new_w | |
| if current_row: | |
| rows.append(np.hstack(current_row)) | |
| if rows: | |
| max_row_w = max(r.shape[1] for r in rows) | |
| padded_rows = [] | |
| for r in rows: | |
| pad_w = max_row_w - r.shape[1] | |
| if pad_w > 0: | |
| pad = np.full((target_h, pad_w, 3), 255, dtype=np.uint8) | |
| r = np.hstack([r, pad]) | |
| padded_rows.append(r) | |
| return np.vstack(padded_rows) | |
| return None | |
| def extract_strat_number(filepath): | |
| name = Path(filepath).stem | |
| nums = re.findall(r'\d+(?:\.\d+)?', name) | |
| if nums: | |
| try: | |
| return float(nums[-1]) | |
| except ValueError: | |
| pass | |
| return 0.0 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 4. PLOT GENERATORS (TYSON, TAI & STRATIGRAPHIC PLOTS) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def plot_tyson_ternary(df, out_path, ref_img_str): | |
| IMG_W, IMG_H = 736, 610 | |
| fig = plt.figure(figsize=(20, 11)) | |
| ax = fig.add_axes([0.02, 0.05, 0.56, 0.88]) | |
| ax.set_xlim(-60, IMG_W + 60) | |
| ax.set_ylim(IMG_H + 60, -80) | |
| ax.set_aspect("equal") | |
| ax.axis("off") | |
| ref_img_path = Path(ref_img_str) | |
| if ref_img_path.exists(): | |
| try: | |
| img = plt.imread(str(ref_img_path)) | |
| ax.imshow(img, extent=[0, IMG_W - 1, IMG_H - 1, 0], aspect="auto", zorder=1, alpha=1.0) | |
| except Exception as e: | |
| print(f" β οΈ Reference image could not be loaded: {e}") | |
| xs = [tc(row["AOM_area_pct"], row["Palynomorph_area_pct"], row["Phytoclast_area_pct"])[0] for _, row in df.iterrows()] | |
| ys = [tc(row["AOM_area_pct"], row["Palynomorph_area_pct"], row["Phytoclast_area_pct"])[1] for _, row in df.iterrows()] | |
| ax.scatter(xs, ys, c="#1A1A2E", s=80, zorder=6, alpha=0.92, edgecolors="white", linewidth=1.0) | |
| ma, mp, mh = df["AOM_area_pct"].mean(), df["Palynomorph_area_pct"].mean(), df["Phytoclast_area_pct"].mean() | |
| mx, my = tc(ma, mp, mh) | |
| ax.scatter([mx], [my], c=MEAN_COLOR, s=300, zorder=7, edgecolors="white", linewidth=1.5, marker="*") | |
| pad = 22 | |
| ax.text(_PX["aom"][0] - pad, _PX["aom"][1] + pad, "AOM\n(Amorphous\nOrganic Matter)", ha="right", va="top", fontsize=10, fontweight="bold", color=COLORS["AOM"], zorder=8) | |
| ax.text(_PX["pal"][0] + pad, _PX["pal"][1] + pad, "Palynomorphs\n(Spores/Pollen/\nMicroplankton)", ha="left", va="top", fontsize=10, fontweight="bold", color=COLORS["Palynomorph"], zorder=8) | |
| ax.text(_PX["phy"][0], _PX["phy"][1] - pad, "Phytoclasts\n(Wood/Plant Debris)", ha="center", va="bottom", fontsize=10, fontweight="bold", color=COLORS["Phytoclast"], zorder=8) | |
| fig.text(0.30, 0.995, "Tyson (1995) Ternary Plot β Palynofacies Analysis", ha="center", va="top", fontsize=14, fontweight="bold") | |
| fig.text(0.30, 0.958, f"n = {len(df)} samples | {datetime.now().strftime('%Y-%m-%d')}", ha="center", va="top", fontsize=11, color="#555555") | |
| ax_leg = fig.add_axes([0.60, 0.05, 0.38, 0.88]) | |
| ax_leg.axis("off") | |
| y_cursor = 0.98 | |
| def leg_title(text, y): | |
| ax_leg.text(0.0, y, text, transform=ax_leg.transAxes, fontsize=11, fontweight="bold", color="#1A1A2E", va="top") | |
| return y - 0.045 | |
| def leg_item(color, label, y, marker=None): | |
| if marker == "*": | |
| ax_leg.scatter([0.018], [y - 0.012], s=220, c=color, marker="*", transform=ax_leg.transAxes, zorder=5, edgecolors="white", linewidth=0.8, clip_on=False) | |
| elif marker == "o": | |
| ax_leg.scatter([0.018], [y - 0.012], s=80, c=color, marker="o", transform=ax_leg.transAxes, zorder=5, edgecolors="white", linewidth=0.8, clip_on=False) | |
| else: | |
| rect = mpatches.FancyBboxPatch((0.0, y - 0.026), 0.038, 0.028, boxstyle="round,pad=0.002", facecolor=color, edgecolor="#999", linewidth=0.7, transform=ax_leg.transAxes, clip_on=False) | |
| ax_leg.add_patch(rect) | |
| ax_leg.text(0.052, y - 0.009, label, transform=ax_leg.transAxes, fontsize=9.2, va="center", color="#222222") | |
| return y - 0.042 | |
| y_cursor = leg_title("Tyson (1995) Facies Fields", y_cursor) | |
| ax_leg.plot([0, 1], [y_cursor + 0.008, y_cursor + 0.008], color="#CCCCCC", linewidth=0.8, transform=ax_leg.transAxes) | |
| y_cursor -= 0.008 | |
| for field in TYSON_FIELDS: | |
| label = f" {field['num']:>4s} {field['name']}" | |
| y_cursor = leg_item(field["color"], label, y_cursor) | |
| y_cursor -= 0.018 | |
| ax_leg.plot([0, 1], [y_cursor + 0.008, y_cursor + 0.008], color="#CCCCCC", linewidth=0.8, transform=ax_leg.transAxes) | |
| y_cursor = leg_title("Statistics & Symbols", y_cursor) | |
| y_cursor = leg_item(COLORS["AOM"], f"AOM (mean {ma:.1f}%)", y_cursor) | |
| y_cursor = leg_item(COLORS["Palynomorph"], f"Palynomorph (mean {mp:.1f}%)", y_cursor) | |
| y_cursor = leg_item(COLORS["Phytoclast"], f"Phytoclast (mean {mh:.1f}%)", y_cursor) | |
| y_cursor = leg_item("#1A1A2E", "Sample Point", y_cursor, marker="o") | |
| y_cursor = leg_item(MEAN_COLOR, "Mean Data Point", y_cursor, marker="*") | |
| plt.savefig(out_path, dpi=200, bbox_inches="tight", facecolor="white") | |
| plt.close() | |
| def plot_tai_visualizer(pal_crop, mean_tai, out_path): | |
| fig = plt.figure(figsize=(10, 6)) | |
| ax_scale = fig.add_axes([0.1, 0.6, 0.8, 0.15]) | |
| cmap = mcolors.LinearSegmentedColormap.from_list("tai", ["#FFFFE0", "#FFD700", "#FF8C00", "#8B4513", "#222222"]) | |
| gradient = np.linspace(1, 5, 256) | |
| gradient = np.vstack((gradient, gradient)) | |
| ax_scale.imshow(gradient, aspect='auto', cmap=cmap, extent=[1, 5, 0, 1]) | |
| ax_scale.set_xlim(1, 5) | |
| ax_scale.set_yticks([]) | |
| ax_scale.set_xticks([1, 2, 3, 4, 5]) | |
| ax_scale.set_xticklabels(["1\nImmature", "2\nEarly Mature", "3\nMature\n(Oil Window)", "4\nLate Mature\n(Wet Gas)", "5\nOvermature\n(Dry Gas)"]) | |
| ax_scale.set_title("Thermal Alteration Index (TAI) Scale & Average Palynomorph Coloration", pad=20, fontsize=14, fontweight="bold") | |
| if mean_tai is not None: | |
| ax_scale.annotate(f'Predicted TAI (median): {mean_tai:.2f}', xy=(mean_tai, 1.0), xytext=(mean_tai, 1.8), | |
| arrowprops=dict(facecolor='#E91E63', edgecolor='none', width=2, headwidth=10), | |
| fontsize=12, color='#E91E63', ha='center', fontweight='bold', clip_on=False) | |
| if pal_crop is not None and pal_crop.size > 0: | |
| ax_img = fig.add_axes([0.15, 0.05, 0.7, 0.4]) | |
| ax_img.imshow(pal_crop) | |
| ax_img.axis('off') | |
| ax_img.set_title("Palynomorphs Used for TAI (illumination-normalized collage)", fontsize=11, color="#333333") | |
| else: | |
| fig.text(0.5, 0.25, "No Palynomorph detected for visualization.", ha="center", fontsize=12, color="gray", style="italic") | |
| plt.savefig(out_path, dpi=200, bbox_inches="tight", facecolor="white") | |
| plt.close(fig) | |
| def plot_stratigraphic_curves(df, out_path): | |
| """Draws stratigraphic relative-abundance curves for the given DataFrame. | |
| If a 'TAI' column exists, a fourth panel with the TAI curve is added.""" | |
| y_pos = np.arange(len(df)) | |
| y_labels = df['Filename'].tolist() | |
| has_tai = "TAI" in df.columns and df["TAI"].notna().any() | |
| ncols = 4 if has_tai else 3 | |
| fig, axes = plt.subplots(1, ncols, figsize=(12 if ncols == 3 else 15.5, 8), sharey=True) | |
| fig.suptitle("Stratigraphic Relative Abundance Curves", fontsize=16, fontweight='bold', y=0.95) | |
| groups = [ | |
| ("AOM_area_pct", "AOM (%)", COLORS["AOM"]), | |
| ("Palynomorph_area_pct", "Palynomorph (%)", COLORS["Palynomorph"]), | |
| ("Phytoclast_area_pct", "Phytoclast (%)", COLORS["Phytoclast"]) | |
| ] | |
| for ax, (col, title, color) in zip(axes[:3], groups): | |
| ax.plot(df[col], y_pos, marker='o', linestyle='-', color=color, linewidth=2, markersize=6) | |
| ax.fill_betweenx(y_pos, 0, df[col], color=color, alpha=0.3) | |
| ax.set_title(title, fontsize=12, fontweight='bold', color=color) | |
| ax.set_xlim(0, 100) | |
| ax.set_ylim(max(y_pos) + 0.5, min(y_pos) - 0.5) | |
| ax.grid(True, linestyle='--', alpha=0.6) | |
| ax.set_xlabel("Relative Area (%)") | |
| if has_tai: | |
| ax = axes[3] | |
| ax.axvspan(2.5, 3.0, color="#FFD54F", alpha=0.25, label="Oil window") | |
| ax.axvspan(3.0, 3.7, color="#FFAB91", alpha=0.25, label="Wet gas") | |
| ax.plot(df["TAI"], y_pos, marker='s', linestyle='-', color="#8B4513", linewidth=2, markersize=6) | |
| ax.set_title("TAI (normalized)", fontsize=12, fontweight='bold', color="#8B4513") | |
| ax.set_xlim(1, 5) | |
| ax.grid(True, linestyle='--', alpha=0.6) | |
| ax.set_xlabel("Thermal Alteration Index") | |
| ax.legend(loc="lower right", fontsize=8) | |
| axes[0].set_yticks(y_pos) | |
| axes[0].set_yticklabels(y_labels, fontsize=10) | |
| axes[0].set_ylabel("Stratigraphic Sequence (File Names)", fontsize=12, fontweight='bold') | |
| plt.tight_layout(rect=[0, 0, 1, 0.93]) | |
| plt.savefig(out_path, dpi=300, bbox_inches="tight", facecolor="white") | |
| plt.close(fig) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 5. MAIN PREDICTION FUNCTION (SINGLE IMAGE) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_microscope_image(img_rgb, magnification, conf_thresh, selected_classes, show_boxes, | |
| norm_mode=MODE_FLAT, blank_img=None, calib_file=None): | |
| NONE5 = (None, None, None, None) | |
| if model is None: | |
| return (*NONE5, "## β Error: model file 'best.pt' was not found. Please check the folder.") | |
| if img_rgb is None: | |
| return (*NONE5, "## β οΈ Please upload an image to analyze.") | |
| class_ids = [CLASS_NAMES.index(c) for c in selected_classes if c in CLASS_NAMES] | |
| if not class_ids: | |
| return (*NONE5, "## β οΈ Please select at least one class to detect.") | |
| if img_rgb.ndim == 2: | |
| img_rgb = np.stack([img_rgb] * 3, axis=-1) | |
| img_rgb = np.ascontiguousarray(img_rgb[..., :3]) | |
| if blank_img is not None and blank_img.ndim == 2: | |
| blank_img = np.stack([blank_img] * 3, axis=-1) | |
| mag = int(magnification) | |
| calib = load_calib(calib_file) | |
| results = model(_to_model_input(img_rgb), conf=conf_thresh, iou=IOU_THRESH, verbose=False) | |
| # Illumination estimation runs BEFORE the class filter (all detected objects are excluded) | |
| prep = build_prep(img_rgb, results[0] if len(results) > 0 else None, norm_mode, blank_img) | |
| if len(results) > 0: | |
| valid_indices = [i for i, cls_id in enumerate(results[0].boxes.cls) if int(cls_id) in class_ids] | |
| results[0].boxes = results[0].boxes[valid_indices] | |
| if results[0].masks is not None: | |
| results[0].masks = results[0].masks[valid_indices] | |
| counts = defaultdict(int) | |
| areas_px = defaultdict(float) | |
| h, w = img_rgb.shape[:2] | |
| total_pixels = h * w | |
| measurements = [] | |
| pal_crops = [] | |
| for r in results: | |
| if r.masks is None: continue | |
| for poly, cls_id in zip(r.masks.xy, r.boxes.cls): | |
| cls_name = CLASS_NAMES[int(cls_id)] | |
| rast = rasterize_roi(poly, h, w) | |
| if rast is None: continue | |
| roi, mask = rast | |
| counts[cls_name] += 1 | |
| areas_px[cls_name] += float(mask.sum()) | |
| if cls_name == "Palynomorph": | |
| meas = measure_palynomorph(prep, roi, mask, calib) | |
| if meas is not None: | |
| measurements.append(meas) | |
| x1, y1, x2, y2 = roi | |
| crop = prep["norm_rgb"][y1:y2, x1:x2] # collage uses normalized colors | |
| if crop.size > 0: | |
| pal_crops.append(crop) | |
| total_pal_px = sum(areas_px.get(g, 0) for g in PALYNO_GROUPS) | |
| total_pal_count = sum(counts.get(g, 0) for g in PALYNO_GROUPS) | |
| aom_area_pct = (areas_px.get("AOM", 0) / total_pal_px * 100) if total_pal_px > 0 else 0.0 | |
| pal_area_pct = (areas_px.get("Palynomorph", 0) / total_pal_px * 100) if total_pal_px > 0 else 0.0 | |
| phy_area_pct = (areas_px.get("Phytoclast", 0) / total_pal_px * 100) if total_pal_px > 0 else 0.0 | |
| aom_count_pct = (counts.get("AOM", 0) / total_pal_count * 100) if total_pal_count > 0 else 0.0 | |
| pal_count_pct = (counts.get("Palynomorph", 0) / total_pal_count * 100) if total_pal_count > 0 else 0.0 | |
| phy_count_pct = (counts.get("Phytoclast", 0) / total_pal_count * 100) if total_pal_count > 0 else 0.0 | |
| total_um2 = pixels_to_um2(total_pixels, mag) | |
| aom_um2 = pixels_to_um2(areas_px.get("AOM", 0), mag) | |
| pal_um2 = pixels_to_um2(areas_px.get("Palynomorph", 0), mag) | |
| phy_um2 = pixels_to_um2(areas_px.get("Phytoclast", 0), mag) | |
| # ββ TAI summary and quality warnings ββ | |
| info = prep["info"] | |
| warnings_ = list(info["warnings"]) | |
| if calib.get("note"): warnings_.append(calib["note"]) | |
| if not calib["calibrated"]: | |
| warnings_.append("TAI curve is the built-in default and is NOT calibrated to your microscope/camera. " | |
| "Use the π― TAI Calibration tab with reference samples of known TAI for absolute values.") | |
| elif calib.get("norm_mode") and calib["norm_mode"] != norm_mode: | |
| warnings_.append(f"Calibration was fitted with '{calib['norm_mode']}' but this run uses '{norm_mode}'.") | |
| mean_tai = None | |
| if measurements: | |
| tais = np.array([m["tai"] for m in measurements]) | |
| mean_tai = float(np.median(tais)) | |
| q1, q3 = np.percentile(tais, [25, 75]) | |
| med = lambda k: float(np.median([m[k] for m in measurements])) | |
| if len(measurements) < 5: | |
| warnings_.append(f"Only {len(measurements)} palynomorph(s) measured; TAI is statistically weak (aim for β₯ 20).") | |
| if med("od_y") > 1.8: | |
| warnings_.append("Palynomorphs are almost opaque (OD > 1.8); TAI saturates near 4.5β5 and may be underestimated.") | |
| tai_str = (f"**{mean_tai:.2f}** ({maturity_label(mean_tai)}) β median of {len(measurements)} palynomorphs, " | |
| f"SD {tais.std():.2f}, IQR {q1:.2f}β{q3:.2f}") | |
| color_row = (f"| Palynomorph colour (median) | OD(Y) {med('od_y'):.2f} Β· OD R/G/B " | |
| f"{med('od_r'):.2f}/{med('od_g'):.2f}/{med('od_b'):.2f} Β· L* {med('L'):.0f} Β· " | |
| f"b* {med('b'):.0f} Β· hue {med('hue'):.0f}Β° |") | |
| else: | |
| tai_str = "*No palynomorph was detected, so TAI could not be calculated.*" | |
| color_row = "" | |
| annotated_bgr = results[0].plot(line_width=3, font_size=7, boxes=show_boxes) | |
| annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB) | |
| df_plot = pd.DataFrame([{ | |
| "AOM_area_pct": aom_area_pct, | |
| "Palynomorph_area_pct": pal_area_pct, | |
| "Phytoclast_area_pct": phy_area_pct | |
| }]) | |
| plot_path = "tyson_ternary_plot.png" | |
| ref_image_name = "Screenshot 2026-06-06 222542.jpg" | |
| plot_tyson_ternary(df_plot, plot_path, ref_image_name) | |
| composite_pal_crop = make_collage(pal_crops) | |
| tai_plot_path = "tai_visualizer_plot.png" | |
| plot_tai_visualizer(composite_pal_crop, mean_tai, tai_plot_path) | |
| qc_img = make_qc_image(img_rgb, prep["norm_rgb"]) | |
| bg_txt = "β" if info["bg_frac"] is None else f"{info['bg_frac'] * 100:.1f}%" | |
| nu_txt = "β" if info["nonuni"] is None else f"{info['nonuni'] * 100:.1f}%" | |
| warn_md = "".join(f"\n> β οΈ {x}" for x in warnings_) | |
| report_md = f""" | |
| ### π Quantitative Palynofacies Analysis Report | |
| * **Thermal Alteration Index (illumination-normalized TAI):** {tai_str} | |
| #### π Component Distribution Table | |
| | Palynofacies Group | Field (Pixel) | Actual Area (Β΅mΒ²) | Relative Area (%) | Count | Relative abundance (%) | | |
| | :--- | :--- | :--- | :--- | :--- | :--- | | |
| | π΄ **AOM** | {areas_px.get('AOM', 0):,.0f} | {aom_um2:,.1f} | **{aom_area_pct:.2f}%** | {counts.get('AOM', 0)} | {aom_count_pct:.2f}% | | |
| | π’ **Palynomorph** | {areas_px.get('Palynomorph', 0):,.0f} | {pal_um2:,.1f} | **{pal_area_pct:.2f}%** | {counts.get('Palynomorph', 0)} | {pal_count_pct:.2f}% | | |
| | π΅ **Phytoclast** | {areas_px.get('Phytoclast', 0):,.0f} | {phy_um2:,.1f} | **{phy_area_pct:.2f}%** | {counts.get('Phytoclast', 0)} | {phy_count_pct:.2f}% | | |
| | βͺ *Background* | {areas_px.get('Background', 0):,.0f} | β | β | {counts.get('Background', 0)} | β | | |
| * **Total Resolution:** {w}x{h} ({total_pixels:,.0f} pixels) | |
| * **Physical Area Analyzed:** {total_um2:,.1f} Β΅mΒ² ({magnification}x under the lens) | |
| #### ποΈ Color Normalization QC | |
| | Parameter | Value | | |
| | :--- | :--- | | |
| | Method | {info['method']} | | |
| | Estimated illuminant white point (sRGB) | {info['white_srgb'][0]}, {info['white_srgb'][1]}, {info['white_srgb'][2]} | | |
| | Background pixels used | {bg_txt} | | |
| | Illumination non-uniformity (vignetting) | {nu_txt} | | |
| {color_row} | |
| | TAI calibration | {calib['source']} | | |
| {warn_md} | |
| """ | |
| return annotated_rgb, plot_path, tai_plot_path, qc_img, report_md | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 6. BATCH & STRATIGRAPHIC ANALYSIS FUNCTION | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _read_image_rgb(fpath): | |
| with open(fpath, "rb") as stream: | |
| bytes_arr = bytearray(stream.read()) | |
| img_bgr = cv2.imdecode(np.asarray(bytes_arr, dtype=np.uint8), cv2.IMREAD_COLOR) | |
| return None if img_bgr is None else cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) | |
| def _paths_from_files(files): | |
| out = [] | |
| for f in files or []: | |
| p = _file_path(f) | |
| if p: out.append(p) | |
| return out | |
| def process_batch_images(files, magnification, conf_thresh, selected_classes, | |
| norm_mode=MODE_FLAT, calib_file=None): | |
| if model is None: | |
| return None, "## β Error: model file 'best.pt' was not found." | |
| if not files: | |
| return None, "## β οΈ Please upload files to analyze." | |
| file_paths = _paths_from_files(files) | |
| # Sort by depth (last number in the file name) | |
| sorted_files = sorted(file_paths, key=extract_strat_number) | |
| calib = load_calib(calib_file) | |
| results_list, failures = [], [] | |
| for fpath in sorted_files: | |
| try: | |
| img_rgb = _read_image_rgb(fpath) | |
| if img_rgb is None: | |
| failures.append(f"{Path(fpath).name}: unreadable image"); continue | |
| h, w = img_rgb.shape[:2] | |
| res = model(_to_model_input(img_rgb), conf=conf_thresh, iou=IOU_THRESH, verbose=False) | |
| r = res[0] | |
| areas_px = defaultdict(float) | |
| meas = [] | |
| if r.masks is not None: | |
| prep = build_prep(img_rgb, r, norm_mode) | |
| for poly, cls_id in zip(r.masks.xy, r.boxes.cls): | |
| cls_name = CLASS_NAMES[int(cls_id)] | |
| if cls_name not in PALYNO_GROUPS: continue | |
| rast = rasterize_roi(poly, h, w) | |
| if rast is None: continue | |
| roi, mask = rast | |
| areas_px[cls_name] += float(mask.sum()) | |
| if cls_name == "Palynomorph": | |
| m = measure_palynomorph(prep, roi, mask, calib) | |
| if m is not None: meas.append(m) | |
| total = sum(areas_px.values()) | |
| if total > 0: | |
| results_list.append({ | |
| "Filename": Path(fpath).name, | |
| "Depth": extract_strat_number(fpath), | |
| "AOM_area_pct": (areas_px.get("AOM", 0) / total) * 100, | |
| "Palynomorph_area_pct": (areas_px.get("Palynomorph", 0) / total) * 100, | |
| "Phytoclast_area_pct": (areas_px.get("Phytoclast", 0) / total) * 100, | |
| "TAI": float(np.median([m["tai"] for m in meas])) if meas else np.nan, | |
| "n_palyno": len(meas), | |
| }) | |
| except Exception as e: | |
| failures.append(f"{Path(fpath).name}: {type(e).__name__}: {e}") | |
| if not results_list: | |
| msg = "## β οΈ Analiz edilemedi." | |
| if failures: msg += "\n\n" + "\n".join(f"* {f}" for f in failures) | |
| return None, msg | |
| df = pd.DataFrame(results_list).sort_values("Depth") | |
| plot_path = "stratigraphic_log.png" | |
| plot_stratigraphic_curves(df, plot_path) | |
| report_md = ("### π Stratigraphic Log Results\n\n" | |
| "| Depth | Filename | AOM (%) | Palynomorph (%) | Phytoclast (%) | TAI | n palyno |\n" | |
| "|---|---|---|---|---|---|---|\n") | |
| for _, row in df.iterrows(): | |
| tai_txt = "β" if pd.isna(row["TAI"]) else f"{row['TAI']:.2f}" | |
| report_md += (f"| {row['Depth']:g} | **{row['Filename']}** | {row['AOM_area_pct']:.1f} | " | |
| f"{row['Palynomorph_area_pct']:.1f} | {row['Phytoclast_area_pct']:.1f} | " | |
| f"{tai_txt} | {int(row['n_palyno'])} |\n") | |
| report_md += f"\n*Normalization:* {norm_mode} Β· *TAI calibration:* {calib['source']}\n" | |
| if not calib["calibrated"]: | |
| report_md += "\n> β οΈ TAI curve is the built-in default (not calibrated). Relative trends are reliable; absolute values need calibration.\n" | |
| if failures: | |
| report_md += "\n> β οΈ Skipped files:\n" + "\n".join(f"> * {f}" for f in failures) + "\n" | |
| return plot_path, report_md | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 6b. TAI CALIBRATION (from reference samples with known TAI) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def calibrate_tai(files, conf_thresh, norm_mode): | |
| """Builds a monotone OD(Y)->TAI curve from images whose file names contain a known | |
| TAI value such as 'TAI3.5' / 'tai_2', and returns a downloadable JSON.""" | |
| if model is None: | |
| return None, "## β Error: model file 'best.pt' was not found." | |
| paths = _paths_from_files(files) | |
| if not paths: | |
| return None, "## β οΈ Upload images with a known TAI value in the file name (e.g. `S12_TAI2.5.jpg`)." | |
| default_calib = load_calib(None) | |
| rows, skipped = [], [] | |
| for fpath in paths: | |
| name = Path(fpath).name | |
| m = re.search(r"tai[\s_\-]*(\d(?:[.,]\d+)?)", Path(fpath).stem, re.IGNORECASE) | |
| if not m: | |
| skipped.append(f"{name}: no 'TAI<value>' in filename"); continue | |
| known = float(m.group(1).replace(",", ".")) | |
| try: | |
| img_rgb = _read_image_rgb(fpath) | |
| if img_rgb is None: | |
| skipped.append(f"{name}: unreadable"); continue | |
| h, w = img_rgb.shape[:2] | |
| r = model(_to_model_input(img_rgb), conf=conf_thresh, iou=IOU_THRESH, verbose=False)[0] | |
| if r.masks is None: | |
| skipped.append(f"{name}: nothing detected"); continue | |
| prep = build_prep(img_rgb, r, norm_mode) | |
| vals = [] | |
| for poly, cls_id in zip(r.masks.xy, r.boxes.cls): | |
| if CLASS_NAMES[int(cls_id)] != "Palynomorph": continue | |
| rast = rasterize_roi(poly, h, w) | |
| if rast is None: continue | |
| mm = measure_palynomorph(prep, rast[0], rast[1], default_calib) | |
| if mm is not None: vals.append(mm["od_y"]) | |
| if len(vals) < 3: | |
| skipped.append(f"{name}: fewer than 3 palynomorphs"); continue | |
| rows.append({"File": name, "TAI_known": known, "OD_Y": float(np.median(vals)), "n": len(vals)}) | |
| except Exception as e: | |
| skipped.append(f"{name}: {type(e).__name__}: {e}") | |
| skip_md = ("\n\n> β οΈ Skipped:\n" + "\n".join(f"> * {s}" for s in skipped)) if skipped else "" | |
| df = pd.DataFrame(rows) | |
| if len(df) < 3 or df["TAI_known"].nunique() < 3: | |
| return None, ("## β οΈ Need at least 3 usable images covering β₯ 3 different TAI levels " | |
| "(ideally 2+ images per level)." + skip_md) | |
| xb, yb = isotonic_fit(df["OD_Y"].values, df["TAI_known"].values) | |
| if len(xb) < 2: | |
| return None, "## β οΈ OD and known TAI are not monotonically related in these images; check labels/segmentation." + skip_md | |
| df["TAI_fit"] = np.interp(df["OD_Y"], xb, yb) | |
| rmse = float(np.sqrt(((df["TAI_fit"] - df["TAI_known"]) ** 2).mean())) | |
| rho = float(np.corrcoef(df["OD_Y"].rank(), df["TAI_known"].rank())[0, 1]) | |
| payload = {"version": 1, "feature": "od_y", "norm_mode": norm_mode, | |
| "anchors": [[float(a), float(b)] for a, b in zip(xb, yb)], | |
| "n_images": int(len(df)), "created": datetime.now().isoformat(timespec="seconds")} | |
| tmp = tempfile.NamedTemporaryFile(prefix="tai_calibration_", suffix=".json", delete=False, mode="w", encoding="utf-8") | |
| json.dump(payload, tmp, indent=2); tmp.close() | |
| md = "### π― TAI Calibration Result\n\n| File | Known TAI | OD(Y) | Fitted TAI | n |\n|---|---|---|---|---|\n" | |
| for _, rw in df.sort_values("TAI_known").iterrows(): | |
| md += f"| {rw['File']} | {rw['TAI_known']:.2f} | {rw['OD_Y']:.3f} | {rw['TAI_fit']:.2f} | {int(rw['n'])} |\n" | |
| md += (f"\n* **Spearman Ο (OD vs known TAI):** {rho:.2f} Β· **RMSE:** {rmse:.2f} TAI units Β· " | |
| f"**Normalization used:** {norm_mode}\n" | |
| "* Download the JSON below, then either upload it in the analysis tabs or commit it to the Space as " | |
| f"`{CALIB_REPO_PATH}` to make it the default.\n" | |
| "* Use the **same normalization mode** for later analyses. The curve is clamped at the first/last anchor " | |
| "(no extrapolation), so include samples spanning your expected TAI range.") | |
| if rho < 0.8: | |
| md += "\n\n> β οΈ Weak rank correlation β check TAI labels, focus/exposure consistency and segmentation quality." | |
| return tmp.name, md + skip_md | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 7. GRADIO WEB INTERFACE (TABBED) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# π¬ PalyTOAE β Palynofacies & TAI AI Analyzer") | |
| gr.Markdown("Upload your palynology images taken under the microscope. Perform single detailed analysis or multiple-image stratigraphic curve generation.") | |
| with gr.Tabs(): | |
| with gr.TabItem("πΌοΈ Single Image Analysis"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| input_img = gr.Image(type="numpy", label="Upload or Take Microscope Image", sources=["upload", "clipboard", "webcam"]) | |
| input_mag = gr.Radio(choices=["10", "20", "40"], value="10", label="Objective Magnification") | |
| input_classes = gr.CheckboxGroup(choices=CLASS_NAMES, value=["AOM", "Palynomorph", "Phytoclast"], label="Select Classes to Detect/Show") | |
| input_conf = gr.Slider(minimum=0.05, maximum=0.95, value=0.25, step=0.05, label="Confidence (Precision) Threshold") | |
| input_show_boxes = gr.Checkbox(value=True, label="Show Bounding Boxes") | |
| with gr.Accordion("ποΈ Color normalization & TAI calibration", open=False): | |
| input_norm = gr.Dropdown(choices=NORM_MODES, value=MODE_FLAT, label="Illumination / white-balance normalization", | |
| info="Removes microscope-, lamp- and exposure-dependent color differences before TAI.") | |
| input_blank = gr.Image(type="numpy", label="Blank slide photo (optional, same settings)", sources=["upload"]) | |
| input_calib = gr.File(file_types=[".json"], label="TAI calibration file (optional)") | |
| submit_btn = gr.Button("π Analyze Single Image", variant="primary") | |
| with gr.Column(scale=2): | |
| with gr.Tabs(): | |
| with gr.TabItem("πΌοΈ Segmentation Output"): | |
| output_img = gr.Image(label="YOLO AI Masks") | |
| with gr.TabItem("π Tyson Triangle Diagram"): | |
| output_plot = gr.Image(label="Tyson (1995) Ternary Plot") | |
| with gr.TabItem("π‘οΈ TAI Visualizer (Average)"): | |
| output_tai_plot = gr.Image(label="Thermal Alteration Index Scale & Collage") | |
| with gr.TabItem("ποΈ Color Normalization QC"): | |
| output_qc = gr.Image(label="Raw vs. normalized image") | |
| output_report = gr.Markdown(value="*Upload an image and click the 'Analyze' button to see the results.*") | |
| submit_btn.click( | |
| fn=process_microscope_image, | |
| inputs=[input_img, input_mag, input_conf, input_classes, input_show_boxes, | |
| input_norm, input_blank, input_calib], | |
| outputs=[output_img, output_plot, output_tai_plot, output_qc, output_report] | |
| ) | |
| with gr.TabItem("π Stratigraphy / Batch Analysis"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("**Note:** The file names of the uploaded photos must contain a number indicating depth/order (e.g. `sample_1.5.jpg`, `sample_12.jpg`). The AI reads these numbers, sorts the samples and draws the log plot. Each sample is normalized against its own background, so different microscopes or lighting conditions do not distort the TAI curve.") | |
| batch_files = gr.File(file_count="multiple", file_types=["image"], label="Upload Multiple Sample Images") | |
| batch_mag = gr.Radio(choices=["10", "20", "40"], value="10", label="Objective Magnification") | |
| batch_classes = gr.CheckboxGroup(choices=CLASS_NAMES, value=["AOM", "Palynomorph", "Phytoclast"], label="Select Classes to Process") | |
| batch_conf = gr.Slider(minimum=0.05, maximum=0.95, value=0.25, step=0.05, label="Confidence Threshold") | |
| batch_norm = gr.Dropdown(choices=NORM_MODES, value=MODE_FLAT, label="Illumination / white-balance normalization") | |
| batch_calib = gr.File(file_types=[".json"], label="TAI calibration file (optional)") | |
| batch_btn = gr.Button("π Generate Stratigraphic Curve", variant="primary") | |
| with gr.Column(scale=2): | |
| output_batch_plot = gr.Image(label="Stratigraphic Relative Abundance Curve") | |
| output_batch_report = gr.Markdown(value="*Upload multiple images to generate a stratigraphic curve.*") | |
| batch_btn.click( | |
| fn=process_batch_images, | |
| inputs=[batch_files, batch_mag, batch_conf, batch_classes, batch_norm, batch_calib], | |
| outputs=[output_batch_plot, output_batch_report] | |
| ) | |
| with gr.TabItem("π― TAI Calibration"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("Upload images of reference samples with a known TAI value. **The file name must contain the TAI value**: `S12_TAI2.5.jpg`, `ref_tai3.jpg`. At least 3 different TAI levels are required (2+ images per level is ideal). The output JSON can be used as a calibration file in the other tabs.") | |
| cal_files = gr.File(file_count="multiple", file_types=["image"], label="Reference images with known TAI") | |
| cal_conf = gr.Slider(minimum=0.05, maximum=0.95, value=0.25, step=0.05, label="Confidence Threshold") | |
| cal_norm = gr.Dropdown(choices=NORM_MODES, value=MODE_FLAT, label="Normalization (use the same later)") | |
| cal_btn = gr.Button("π― Fit calibration curve", variant="primary") | |
| with gr.Column(scale=2): | |
| cal_out_file = gr.File(label="Download calibration JSON") | |
| cal_out_report = gr.Markdown(value="*Upload reference images to fit a calibration curve.*") | |
| cal_btn.click(fn=calibrate_tai, inputs=[cal_files, cal_conf, cal_norm], | |
| outputs=[cal_out_file, cal_out_report]) | |
| if __name__ == "__main__": | |
| demo.launch() |