Download app.py from Bora9/paly: direct link, hf CLI and curl.
- Browser
- Download file 29.1 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
29.1 kB
| import os | |
| import re | |
| 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. AYARLAR & YAPILANDIRMALAR (SETTINGS & CONFIGURATIONS) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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Δ°N YΓKLENMESΔ° | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODEL_PATH = "best.pt" | |
| if os.path.exists(MODEL_PATH): | |
| model = YOLO(MODEL_PATH) | |
| else: | |
| model = None | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 3. YARDIMCI MATEMATΔ°KSEL FONKSΔ°YONLAR | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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 | |
| def estimate_tai(image_rgb, mask_np): | |
| if mask_np.shape != image_rgb.shape[:2]: | |
| mask_np = cv2.resize(mask_np.astype(np.uint8), (image_rgb.shape[1], image_rgb.shape[0]), interpolation=cv2.INTER_NEAREST) | |
| pixels = image_rgb[mask_np == 1] | |
| if len(pixels) < 50: | |
| return None, None | |
| hsv = cv2.cvtColor(np.uint8([pixels]), cv2.COLOR_RGB2HSV)[0] | |
| hue = np.mean(hsv[:, 0]) | |
| val = np.mean(hsv[:, 2]) | |
| sat = np.mean(hsv[:, 1]) | |
| if val < 50: return 4.2, "Overmature (Dry Gas Window)" | |
| elif val < 90: return 3.2, "Late Mature (Wet Gas Window)" | |
| elif val < 140 and sat > 60: return 2.7, "Mature (Oil Window)" | |
| elif hue < 25: return 2.2, "Early Mature" | |
| elif hue < 40: return 1.8, "ImmatureβEarly Mature" | |
| else: return 1.3, "Immature" | |
| 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. GRAFΔ°K ΓRETΔ°CΔ°LERΔ° (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" β οΈ Referans gΓΆrsel yΓΌklenemedi: {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 Average TAI: {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("All Detected Palynomorphs Used for Average TAI (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): | |
| """Verilen DataFrame'e gΓΆre stratigrafik baΔΔ±l bolluk (relative abundance) eΔrisi Γ§izer.""" | |
| # Y-ekseni verileri (Numune/Derinlik sΔ±ralamasΔ±) | |
| y_pos = np.arange(len(df)) | |
| y_labels = df['Filename'].tolist() | |
| fig, axes = plt.subplots(1, 3, figsize=(12, 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, groups): | |
| # Γizgi ve noktalar | |
| ax.plot(df[col], y_pos, marker='o', linestyle='-', color=color, linewidth=2, markersize=6) | |
| # EΔrinin altΔ±nΔ± boyama (Stratigrafik log stili) | |
| 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) # Stratigrafide 1 numara genelde ΓΌsttedir (Top-Down) | |
| ax.grid(True, linestyle='--', alpha=0.6) | |
| ax.set_xlabel("Relative Area (%)") | |
| # Y Eksenine dosya isimlerini yazdΔ±r | |
| 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. ANA TAHMΔ°N FONKSΔ°YONU (TEKΔ°L GΓRSEL) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_microscope_image(img_rgb, magnification, conf_thresh, selected_classes, show_boxes): | |
| if model is None: | |
| return None, None, None, "## β Hata: 'best.pt' model dosyasΔ± bulunamadΔ±. LΓΌtfen klasΓΆrΓΌ kontrol edin." | |
| if img_rgb is None: | |
| return None, None, None, "## β οΈ LΓΌtfen analiz iΓ§in bir resim yΓΌkleyin." | |
| class_ids = [CLASS_NAMES.index(c) for c in selected_classes if c in CLASS_NAMES] | |
| if not class_ids: | |
| return None, None, None, "## β οΈ LΓΌtfen tespit edilecek en az bir sΔ±nΔ±f seΓ§in." | |
| mag = int(magnification) | |
| results = model(img_rgb, conf=conf_thresh, iou=IOU_THRESH, verbose=False) | |
| 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 | |
| tai_scores = [] | |
| pal_crops = [] | |
| for r in results: | |
| if r.masks is None: continue | |
| for mask_t, box, cls_id in zip(r.masks.data, r.boxes.xyxy, r.boxes.cls): | |
| cls_name = CLASS_NAMES[int(cls_id)] | |
| mask_np = mask_t.cpu().numpy() | |
| if mask_np.shape != (h, w): | |
| mask_np = cv2.resize(mask_np.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) | |
| area = float(mask_np.sum()) | |
| counts[cls_name] += 1 | |
| areas_px[cls_name] += area | |
| if cls_name == "Palynomorph": | |
| tai, status = estimate_tai(img_rgb, mask_np) | |
| if tai is not None: | |
| tai_scores.append(tai) | |
| x1, y1, x2, y2 = map(int, box.cpu().numpy()) | |
| x1, y1 = max(0, x1), max(0, y1) | |
| x2, y2 = min(w, x2), min(h, y2) | |
| crop = img_rgb[y1:y2, x1:x2] | |
| 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) | |
| mean_tai = None | |
| if tai_scores: | |
| mean_tai = np.mean(tai_scores) | |
| if mean_tai >= 3.7: maturity = "Overmature (Dry Gas)" | |
| elif mean_tai >= 3.0: maturity = "Late Mature (Wet Gas)" | |
| elif mean_tai >= 2.5: maturity = "Mature (Oil Window)" | |
| elif mean_tai >= 2.0: maturity = "Early Mature" | |
| elif mean_tai >= 1.5: maturity = "ImmatureβEarly Mature" | |
| else: maturity = "Immature" | |
| tai_str = f"**{mean_tai:.2f}** ({maturity}) - *Averaged from {len(pal_crops)} palynomorphs*" | |
| else: | |
| tai_str = "*Palinomorf tespit edilemediΔi iΓ§in TAI hesaplanamadΔ±.*" | |
| 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) | |
| report_md = f""" | |
| ### π Quantitative Palynofacies Analysis Report | |
| * **Thermal Alteration Index (Predicted Average 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} piksel) | |
| * **Physical Area Analyzed:** {total_um2:,.1f} Β΅mΒ² ({magnification}x under the lens) | |
| """ | |
| return annotated_rgb, plot_path, tai_plot_path, report_md | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 6. BATCH & STRATIGRAPHIC ANALΔ°Z FONKSΔ°YONU (GΓNCELLENMΔ°Ε) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_batch_images(files, magnification, conf_thresh, selected_classes): | |
| if model is None: | |
| return None, "## β Hata: 'best.pt' model dosyasΔ± bulunamadΔ±." | |
| if not files: | |
| return None, "## β οΈ LΓΌtfen analiz iΓ§in dosyalarΔ± yΓΌkleyin." | |
| class_ids = [CLASS_NAMES.index(c) for c in selected_classes if c in CLASS_NAMES] | |
| file_paths = [] | |
| for f in files: | |
| if isinstance(f, str): file_paths.append(f) | |
| elif hasattr(f, 'name'): file_paths.append(f.name) | |
| elif isinstance(f, dict) and 'name' in f: file_paths.append(f['name']) | |
| # DerinliΔe gΓΆre sΔ±rala (en kΓΌΓ§ΓΌk derinlik/sayΔ± en altta olacak) | |
| sorted_files = sorted(file_paths, key=extract_strat_number) | |
| results_list = [] | |
| for fpath in sorted_files: | |
| try: | |
| 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) | |
| if img_bgr is None: continue | |
| img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) | |
| h, w = img_rgb.shape[:2] | |
| res = model(img_rgb, conf=conf_thresh, iou=IOU_THRESH, verbose=False) | |
| areas_px = defaultdict(float) | |
| for r in res: | |
| if r.masks is None: continue | |
| for mask_t, cls_id in zip(r.masks.data, r.boxes.cls): | |
| cls_name = CLASS_NAMES[int(cls_id)] | |
| if cls_name in PALYNO_GROUPS: | |
| mask_np = cv2.resize(mask_np := mask_t.cpu().numpy().astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) | |
| areas_px[cls_name] += float(mask_np.sum()) | |
| 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 | |
| }) | |
| except: continue | |
| if not results_list: return None, "## β οΈ Analiz edilemedi." | |
| df = pd.DataFrame(results_list).sort_values("Depth") | |
| # Δ°kinci dosyadan eklenen Stratigrafik 3'lΓΌ eΔri grafiΔini oluΕtur | |
| plot_path = "stratigraphic_log.png" | |
| plot_stratigraphic_curves(df, plot_path) | |
| # Markdown Raporu | |
| report_md = "### π Stratigraphic Log Results\n\n| Depth | Filename | AOM (%) | Palynomorph (%) | Phytoclast (%) |\n|---|---|---|---|---|\n" | |
| for _, row in df.iterrows(): | |
| report_md += f"| {row['Depth']:g} | **{row['Filename']}** | {row['AOM_area_pct']:.1f} | {row['Palynomorph_area_pct']:.1f} | {row['Phytoclast_area_pct']:.1f} |\n" | |
| return plot_path, report_md | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # 7. GRADIO WEB ARAYΓZΓ TASARIMI (SEKMELΔ°) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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") | |
| 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") | |
| 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], | |
| outputs=[output_img, output_plot, output_tai_plot, output_report] | |
| ) | |
| with gr.TabItem("π Stratigraphy / Batch Analysis"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("**Not:** YΓΌklediΔiniz fotoΔraflarΔ±n isimlerinde derinlik/sΔ±ra belirten sayΔ±lar olmalΔ±dΔ±r. (Γrn: `numune_1.5.jpg`, `numune_12.jpg`). AI bunlarΔ± okuyarak sΔ±raya koyar ve ΓΌΓ§lΓΌ log grafiΔi Γ§izer.") | |
| 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_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], | |
| outputs=[output_batch_plot, output_batch_report] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |