File size: 6,385 Bytes
5cc7f8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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 = """
<div style="display:flex;gap:1.5rem;flex-wrap:wrap;align-items:center;justify-content:space-between;">
  <div>
    <h1 style="margin-bottom:0.25rem;">PVC Pipe Counter</h1>
    <p style="margin:0;color:#4d4d4d;font-size:0.95rem;max-width:38rem;">
      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.
    </p>
  </div>
  <div style="min-width:220px;background:#f3f7ff;border-radius:12px;padding:1rem 1.25rem;border:1px solid #d5e1ff;">
    <h3 style="margin-top:0;margin-bottom:0.5rem;font-size:1rem;">Workflow</h3>
    <ol style="margin:0;padding-left:1.1rem;font-size:0.85rem;color:#445;">
      <li>Capture or upload a pipe bundle image.</li>
      <li>Fine-tune the detection thresholds (confidence / IoU).</li>
      <li>Download the annotated result or export the count sheet.</li>
    </ol>
  </div>
</div>
"""

FEATURE_CALLOUT = """
<div style="display:flex;gap:1rem;flex-wrap:wrap;">
  <div style="flex:1 1 220px;background:#fff7ed;border:1px solid #ffd8a8;border-radius:10px;padding:0.85rem;">
    <h4 style="margin:0 0 0.35rem 0;">Visual QA</h4>
    <p style="margin:0;color:#4c3d2b;font-size:0.85rem;">Overlay detections with labeled bounding boxes to cross-check tricky bundles.</p>
  </div>
  <div style="flex:1 1 220px;background:#ecfdf3;border:1px solid #bbf7d0;border-radius:10px;padding:0.85rem;">
    <h4 style="margin:0 0 0.35rem 0;">Adjustable Sensitivity</h4>
    <p style="margin:0;color:#1f492f;font-size:0.85rem;">Control confidence and overlap thresholds to match on-site lighting and camera angles.</p>
  </div>
  <div style="flex:1 1 220px;background:#eef2ff;border:1px solid #c7d2fe;border-radius:10px;padding:0.85rem;">
    <h4 style="margin:0 0 0.35rem 0;">Structured Output</h4>
    <p style="margin:0;color:#1f2563;font-size:0.85rem;">Export-ready table with per-pipe coordinates for downstream reconciliation.</p>
  </div>
</div>
"""

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()