Download app.py from Krrrrish/industrial-surface-defect-segmentation: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/Krrrrish/industrial-surface-defect-segmentation/resolve/main/app.py
- Command line
-
hf download hf://Krrrrish/industrial-surface-defect-segmentation/app.py
-
curl -L -o app.py https://huggingface.co/Krrrrish/industrial-surface-defect-segmentation/resolve/main/app.py
12.7 kB
| """ | |
| Gradio Web Application for Industrial Surface Defect Segmentation | |
| Ready for Hugging Face Spaces Deployment | |
| """ | |
| import os | |
| from pathlib import Path | |
| import cv2 | |
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from models_def import build_model, load_model_with_weights, IMG_H, IMG_W | |
| from utils import ( | |
| CLASS_NAMES, | |
| CLASS_LABELS, | |
| CLASS_COLORS, | |
| DEFAULT_THRESHOLDS, | |
| DEFAULT_MIN_AREAS, | |
| preprocess_image, | |
| predict_with_tta, | |
| apply_postprocess, | |
| create_segmentation_overlay, | |
| compute_defect_diagnostics, | |
| rle_encode | |
| ) | |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| CKPT_DIR = Path(__file__).parent / "models" | |
| CKPT_DIR.mkdir(parents=True, exist_ok=True) | |
| # --------------------------------------------------------------------------- | |
| # Global Model Registry & Lazy Loader | |
| # --------------------------------------------------------------------------- | |
| MODEL_CACHE = {} | |
| MODEL_MAPPING = { | |
| "ResNet-34 U-Net (Pretrained)": "resnet34_unet", | |
| "EfficientNet-B3 U-Net (Pretrained)": "effnet_b3_unet", | |
| "Scratch U-Net (Baseline)": "scratch_unet" | |
| } | |
| def get_model(display_name): | |
| """Loads and caches the requested model architecture and checkpoint.""" | |
| internal_name = MODEL_MAPPING.get(display_name, "resnet34_unet") | |
| if internal_name not in MODEL_CACHE: | |
| model, status = load_model_with_weights(internal_name, ckpt_dir=CKPT_DIR, device=DEVICE) | |
| MODEL_CACHE[internal_name] = (model, status) | |
| return MODEL_CACHE[internal_name] | |
| # --------------------------------------------------------------------------- | |
| # Inference Pipeline | |
| # --------------------------------------------------------------------------- | |
| def run_inspection( | |
| input_image, | |
| model_choice, | |
| use_tta, | |
| th_a, th_b, th_c, th_d, | |
| min_a, min_b, min_c, min_d | |
| ): | |
| if input_image is None: | |
| return ( | |
| None, | |
| "<div style='padding:15px; background-color:#fee2e2; border-radius:8px; color:#b91c1c; font-weight:bold;'>β οΈ Please upload an image or choose one of the examples below.</div>", | |
| pd.DataFrame(), | |
| None, None, None, None, | |
| "No input provided", | |
| "Ready" | |
| ) | |
| # 1. Preprocess | |
| tensor_x, display_rgb = preprocess_image(input_image) | |
| # 2. Model Prediction | |
| thresholds = [th_a, th_b, th_c, th_d] | |
| min_areas = [min_a, min_b, min_c, min_d] | |
| if model_choice == "Ensemble (ResNet-34 + EfficientNet-B3)": | |
| m1, s1 = get_model("ResNet-34 U-Net (Pretrained)") | |
| m2, s2 = get_model("EfficientNet-B3 U-Net (Pretrained)") | |
| p1 = predict_with_tta(m1, tensor_x, tta=use_tta, device=DEVICE) | |
| p2 = predict_with_tta(m2, tensor_x, tta=use_tta, device=DEVICE) | |
| probs = (p1 + p2) / 2.0 | |
| status_msg = f"Ensemble of ResNet-34 & EfficientNet-B3. ({s1} | {s2})" | |
| else: | |
| model, status_msg = get_model(model_choice) | |
| probs = predict_with_tta(model, tensor_x, tta=use_tta, device=DEVICE) | |
| # 3. Post-processing (Thresholding + Connected Components filtering) | |
| binary_masks = apply_postprocess(probs, thresholds=thresholds, min_areas=min_areas) | |
| # 4. Generate Visual Overlays | |
| overlay_img = create_segmentation_overlay(display_rgb, binary_masks, alpha=0.55) | |
| # 5. Extract Analytics & Diagnostics | |
| diagnostics, overall_verdict = compute_defect_diagnostics(binary_masks) | |
| diag_df = pd.DataFrame(diagnostics)[["Label", "Detected", "Components", "Area (px)", "Surface %"]] | |
| # 6. Isolated class masks for preview | |
| mask_a = (binary_masks[0].astype(np.uint8) * 255) | |
| mask_b = (binary_masks[1].astype(np.uint8) * 255) | |
| mask_c = (binary_masks[2].astype(np.uint8) * 255) | |
| mask_d = (binary_masks[3].astype(np.uint8) * 255) | |
| # 7. Formatted RLE strings | |
| rle_lines = [] | |
| for diag in diagnostics: | |
| c_name = diag["Class Name"] | |
| rle = rle_encode(binary_masks[CLASS_NAMES.index(c_name)]) | |
| rle_lines.append(f"{c_name}: {rle if rle else '[CLEAN / NO DEFECT]'}") | |
| full_rle_text = "\n\n".join(rle_lines) | |
| # Status Banner HTML | |
| if "DEFECT" in overall_verdict: | |
| banner_html = ( | |
| f"<div style='padding:12px; background:linear-gradient(90deg, #fee2e2, #fecaca); " | |
| f"border-left: 6px solid #dc2626; border-radius:6px; color:#991b1b; font-size:16px; font-weight:600;'>" | |
| f"β DEFECT DETECTED β Inspection Flagged</div>" | |
| ) | |
| else: | |
| banner_html = ( | |
| f"<div style='padding:12px; background:linear-gradient(90deg, #dcfce7, #bbf7d0); " | |
| f"border-left: 6px solid #16a34a; border-radius:6px; color:#166534; font-size:16px; font-weight:600;'>" | |
| f"β PASSED β Surface Clean / No Anomalies Detected</div>" | |
| ) | |
| return ( | |
| overlay_img, | |
| banner_html, | |
| diag_df, | |
| mask_a, mask_b, mask_c, mask_d, | |
| full_rle_text, | |
| status_msg | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Custom CSS Styling | |
| # --------------------------------------------------------------------------- | |
| CUSTOM_CSS = """ | |
| .gradio-container { | |
| max-width: 1280px !important; | |
| margin: auto !important; | |
| font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
| } | |
| .header-box { | |
| background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); | |
| padding: 24px; | |
| border-radius: 12px; | |
| color: white; | |
| margin-bottom: 20px; | |
| box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); | |
| } | |
| .header-title { | |
| font-size: 26px; | |
| font-weight: 700; | |
| margin-bottom: 6px; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .header-subtitle { | |
| color: #94a3b8; | |
| font-size: 14px; | |
| line-height: 1.5; | |
| } | |
| .legend-pill { | |
| display: inline-block; | |
| padding: 4px 10px; | |
| border-radius: 6px; | |
| font-size: 12px; | |
| font-weight: 600; | |
| margin-right: 8px; | |
| margin-bottom: 4px; | |
| color: #ffffff; | |
| } | |
| """ | |
| HEADER_HTML = """ | |
| <div class="header-box"> | |
| <div class="header-title">π Industrial Surface Defect Segmentation</div> | |
| <div class="header-subtitle"> | |
| Automated pixel-level defect localization and segmentation for industrial metal strip surfaces (128 × 800 px).<br> | |
| Trained with <b>BCEDiceLoss</b> (Foreground Dice 70%, FP Volume 20%, Empty 10%), <b>4-View Flip TTA</b>, and <b>Connected-Component area filtering</b>. | |
| </div> | |
| <div style="margin-top:14px; display:flex; flex-wrap:wrap; gap:8px;"> | |
| <span class="legend-pill" style="background:#dc2626;">β Defect A (Red)</span> | |
| <span class="legend-pill" style="background:#16a34a;">β Defect B (Green)</span> | |
| <span class="legend-pill" style="background:#2563eb;">β Defect C (Cyan/Blue)</span> | |
| <span class="legend-pill" style="background:#d97706;">β Defect D (Orange/Gold)</span> | |
| </div> | |
| </div> | |
| """ | |
| # --------------------------------------------------------------------------- | |
| # Gradio Blocks App Layout | |
| # --------------------------------------------------------------------------- | |
| with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS, title="Industrial Defect Segmentation") as demo: | |
| gr.HTML(HEADER_HTML) | |
| with gr.Row(): | |
| # Left Column: Inputs & Settings | |
| with gr.Column(scale=5): | |
| gr.Markdown("### 1. Upload Strip Image (128 × 800)") | |
| input_image = gr.Image( | |
| label="Strip Image Input", | |
| type="pil", | |
| height=180 | |
| ) | |
| gr.Markdown("### 2. Model & Inference Options") | |
| model_selector = gr.Dropdown( | |
| label="Model Architecture", | |
| choices=[ | |
| "ResNet-34 U-Net (Pretrained)", | |
| "EfficientNet-B3 U-Net (Pretrained)", | |
| "Scratch U-Net (Baseline)", | |
| "Ensemble (ResNet-34 + EfficientNet-B3)" | |
| ], | |
| value="ResNet-34 U-Net (Pretrained)", | |
| interactive=True | |
| ) | |
| tta_toggle = gr.Checkbox( | |
| label="Enable 4-View Test-Time Augmentation (TTA)", | |
| value=True, | |
| info="Averages predictions over original, horizontal, vertical, and diagonal flips." | |
| ) | |
| with gr.Accordion("βοΈ Calibrated Sensitivity & Area Filters", open=False): | |
| gr.Markdown("**Probability Cut-off Thresholds:**") | |
| th_a = gr.Slider(0.05, 0.95, value=DEFAULT_THRESHOLDS[0], step=0.01, label="Defect A Threshold") | |
| th_b = gr.Slider(0.05, 0.95, value=DEFAULT_THRESHOLDS[1], step=0.01, label="Defect B Threshold") | |
| th_c = gr.Slider(0.05, 0.95, value=DEFAULT_THRESHOLDS[2], step=0.01, label="Defect C Threshold") | |
| th_d = gr.Slider(0.05, 0.95, value=DEFAULT_THRESHOLDS[3], step=0.01, label="Defect D Threshold") | |
| gr.Markdown("**Minimum Connected Component Area (px):**") | |
| min_a = gr.Slider(0, 1000, value=DEFAULT_MIN_AREAS[0], step=5, label="Defect A Min Area") | |
| min_b = gr.Slider(0, 1000, value=DEFAULT_MIN_AREAS[1], step=5, label="Defect B Min Area") | |
| min_c = gr.Slider(0, 1000, value=DEFAULT_MIN_AREAS[2], step=10, label="Defect C Min Area") | |
| min_d = gr.Slider(0, 1000, value=DEFAULT_MIN_AREAS[3], step=10, label="Defect D Min Area") | |
| inspect_btn = gr.Button("π Run Defect Inspection", variant="primary", size="lg") | |
| # Right Column: Output Visualizations & Analytics | |
| with gr.Column(scale=7): | |
| gr.Markdown("### 3. Inspection Verdict & Segmentation") | |
| verdict_banner = gr.HTML( | |
| "<div style='padding:12px; background:#f1f5f9; border-radius:6px; color:#475569;'>Click 'Run Defect Inspection' or select an example image below to analyze.</div>" | |
| ) | |
| overlay_display = gr.Image( | |
| label="Color-Coded Defect Segmentation Overlay (128x800)", | |
| type="numpy", | |
| height=200 | |
| ) | |
| with gr.Tabs(): | |
| with gr.TabItem("π Defect Diagnostics Table"): | |
| diag_table = gr.DataFrame( | |
| headers=["Label", "Detected", "Components", "Area (px)", "Surface %"], | |
| label="Summary Analytics", | |
| interactive=False | |
| ) | |
| with gr.TabItem("πΌοΈ Individual Defect Masks"): | |
| with gr.Row(): | |
| mask_a_view = gr.Image(label="Defect A Mask", type="numpy", height=120) | |
| mask_b_view = gr.Image(label="Defect B Mask", type="numpy", height=120) | |
| with gr.Row(): | |
| mask_c_view = gr.Image(label="Defect C Mask", type="numpy", height=120) | |
| mask_d_view = gr.Image(label="Defect D Mask", type="numpy", height=120) | |
| with gr.TabItem("π Kaggle RLE Export"): | |
| rle_output = gr.Textbox( | |
| label="Competition Run-Length Encodings (1-indexed, Column-Major)", | |
| lines=6, | |
| show_copy_button=True | |
| ) | |
| system_status = gr.Textbox( | |
| label="System Status", | |
| value="Models ready on CPU/CUDA", | |
| interactive=False | |
| ) | |
| # ----------------------------------------------------------------------- | |
| # Example Samples for Quick 1-Click Testing | |
| # ----------------------------------------------------------------------- | |
| examples_dir = Path(__file__).parent / "examples" | |
| sample_images = sorted(list(examples_dir.glob("*.png"))) | |
| if sample_images: | |
| gr.Markdown("### π Example Test Images (Click any image to test immediately)") | |
| gr.Examples( | |
| examples=[[str(p)] for p in sample_images], | |
| inputs=[input_image], | |
| label="Curated Test Samples" | |
| ) | |
| # ----------------------------------------------------------------------- | |
| # Event Handlers | |
| # ----------------------------------------------------------------------- | |
| inspect_btn.click( | |
| fn=run_inspection, | |
| inputs=[ | |
| input_image, | |
| model_selector, | |
| tta_toggle, | |
| th_a, th_b, th_c, th_d, | |
| min_a, min_b, min_c, min_d | |
| ], | |
| outputs=[ | |
| overlay_display, | |
| verdict_banner, | |
| diag_table, | |
| mask_a_view, mask_b_view, mask_c_view, mask_d_view, | |
| rle_output, | |
| system_status | |
| ] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |