from __future__ import annotations import gradio as gr import numpy as np from PIL import Image from pipe_counter import Detection, PipeCounter _MODEL: PipeCounter | None = None def get_model() -> PipeCounter: global _MODEL if _MODEL is None: _MODEL = PipeCounter() return _MODEL def _format_detections(detections: list[Detection]) -> list[list[int | float | str]]: rows: list[list[int | float | str]] = [] for idx, det in enumerate(detections, start=1): x1, y1, x2, y2 = det.box rows.append( [ idx, det.label, round(det.confidence, 3), x1, y1, x2, y2, ] ) return rows def count_pipes( image: np.ndarray | None, confidence: float, iou: float, ) -> tuple[Image.Image | None, str, int, list[list[int | float | str]]]: if image is None: return None, "Upload an image to analyze PVC bundles.", 0, [] model = get_model() detections, annotated = model.predict(image, confidence=confidence, iou=iou) count = len(detections) message = ( f"Detected **{count}** pipes at confidence ≥ {confidence:.2f}." if count else "No pipes detected. Try lowering the confidence threshold or uploading a sharper image." ) table = _format_detections(detections) return annotated, message, count, table def reset_view() -> tuple[None, str, int, object]: return None, "Upload an image to begin.", 0, gr.update(value=[]) DESCRIPTION = """

PVC Pipe Counter

Automated counting for pipe bundles inspired by the CountThings workflow. Upload a rack photo, adjust thresholds, and review bounding boxes with per-pipe confidence to accelerate QA and inventory tasks.

Workflow

  1. Capture or upload a pipe bundle image.
  2. Fine-tune the detection thresholds (confidence / IoU).
  3. Download the annotated result or export the count sheet.
""" FEATURE_CALLOUT = """

Visual QA

Overlay detections with labeled bounding boxes to cross-check tricky bundles.

Adjustable Sensitivity

Control confidence and overlap thresholds to match on-site lighting and camera angles.

Structured Output

Export-ready table with per-pipe coordinates for downstream reconciliation.

""" CSS = """ :root { --radius-lg: 14px; } .gradio-container {background: #f5f7fb;} .block {border-radius: var(--radius-lg)!important;} button.primary {background: linear-gradient(135deg,#4361ee,#5e60ce)!important;} footer {display:none!important;} """ def build_demo() -> gr.Blocks: with gr.Blocks(css=CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo: gr.HTML(DESCRIPTION) gr.Markdown(FEATURE_CALLOUT) with gr.Row(equal_height=True): with gr.Column(scale=5, min_width=360): image_input = gr.Image( label="Upload Pipe Bundle", type="numpy", image_mode="RGB", height=360, ) with gr.Accordion("Detection Settings", open=False): confidence_slider = gr.Slider( minimum=0.05, maximum=0.95, value=0.45, step=0.05, label="Confidence Threshold", ) iou_slider = gr.Slider( minimum=0.1, maximum=0.9, value=0.45, step=0.05, label="IoU Threshold", ) run_button = gr.Button("Count Pipes", variant="primary") reset_button = gr.Button("Clear", variant="secondary") status = gr.Markdown("Upload an image to begin.") with gr.Column(scale=7, min_width=420): output_image = gr.Image(label="Detections", show_label=True, height=420) with gr.Row(): count_badge = gr.Number(label="Total Pipes", value=0, precision=0) gr.Markdown("Use the table for inspection and exporting.") table = gr.Dataframe( headers=["#", "Label", "Confidence", "X1", "Y1", "X2", "Y2"], datatype=["number", "str", "number", "number", "number", "number", "number"], interactive=False, ) run_button.click( count_pipes, inputs=[image_input, confidence_slider, iou_slider], outputs=[output_image, status, count_badge, table], ) image_input.upload( count_pipes, inputs=[image_input, confidence_slider, iou_slider], outputs=[output_image, status, count_badge, table], ) reset_button.click( reset_view, outputs=[output_image, status, count_badge, table], ) return demo demo = build_demo() if __name__ == "__main__": demo.launch()