Khunndev Cursor commited on
Commit
0e0cc3e
·
0 Parent(s):

Deploy offline-first PWA with in-browser ONNX inference

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +11 -0
  2. .gitattributes +36 -0
  3. .gitignore +12 -0
  4. Dockerfile +23 -0
  5. KNOWLEDGE.md +172 -0
  6. README.md +81 -0
  7. countmodel.pt +3 -0
  8. credit.png +0 -0
  9. frontend/.gitignore +24 -0
  10. frontend/README.md +73 -0
  11. frontend/eslint.config.js +22 -0
  12. frontend/index.html +14 -0
  13. frontend/package-lock.json +0 -0
  14. frontend/package.json +38 -0
  15. frontend/public/favicon.svg +1 -0
  16. frontend/public/icon.svg +9 -0
  17. frontend/public/icons.svg +24 -0
  18. frontend/public/models/countmodel-640-int8.onnx +3 -0
  19. frontend/public/models/countmodel-640.onnx +3 -0
  20. frontend/public/models/countmodel-int8.onnx +3 -0
  21. frontend/public/models/countmodel.onnx +3 -0
  22. frontend/src/App.css +184 -0
  23. frontend/src/App.tsx +259 -0
  24. frontend/src/assets/hero.png +0 -0
  25. frontend/src/assets/react.svg +1 -0
  26. frontend/src/assets/vite.svg +1 -0
  27. frontend/src/components/DetectionCanvas.tsx +193 -0
  28. frontend/src/components/GroupPanel.tsx +67 -0
  29. frontend/src/index.css +22 -0
  30. frontend/src/lib/clustering.ts +106 -0
  31. frontend/src/lib/constants.ts +17 -0
  32. frontend/src/lib/export.ts +77 -0
  33. frontend/src/lib/i18n.ts +64 -0
  34. frontend/src/lib/inference.ts +202 -0
  35. frontend/src/lib/modelSelect.ts +18 -0
  36. frontend/src/lib/nms.ts +59 -0
  37. frontend/src/lib/preprocess.ts +70 -0
  38. frontend/src/lib/types.ts +31 -0
  39. frontend/src/main.tsx +13 -0
  40. frontend/src/vite-env.d.ts +2 -0
  41. frontend/tsconfig.app.json +25 -0
  42. frontend/tsconfig.json +7 -0
  43. frontend/tsconfig.node.json +24 -0
  44. frontend/vite.config.ts +53 -0
  45. main.py +62 -0
  46. requirements-export.txt +13 -0
  47. requirements-server.txt +4 -0
  48. scripts/build-static.bat +10 -0
  49. scripts/export_onnx.py +106 -0
  50. scripts/test_samples.py +161 -0
.dockerignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ dist
3
+ frontend/node_modules
4
+ frontend/dist
5
+ yolov5
6
+ .git
7
+ __pycache__
8
+ *.pyc
9
+ .env
10
+ test-output
11
+ static
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.onnx.data filter=lfs diff=lfs merge=lfs -text
18
+ *.ot filter=lfs diff=lfs merge=lfs -text
19
+ *.parquet filter=lfs diff=lfs merge=lfs -text
20
+ *.pb filter=lfs diff=lfs merge=lfs -text
21
+ *.pickle filter=lfs diff=lfs merge=lfs -text
22
+ *.pkl filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tar filter=lfs diff=lfs merge=lfs -text
30
+ *.tflite filter=lfs diff=lfs merge=lfs -text
31
+ *.tgz filter=lfs diff=lfs merge=lfs -text
32
+ *.wasm filter=lfs diff=lfs merge=lfs -text
33
+ *.xz filter=lfs diff=lfs merge=lfs -text
34
+ *.zip filter=lfs diff=lfs merge=lfs -text
35
+ *.zst filter=lfs diff=lfs merge=lfs -text
36
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ yolov5/
5
+ test-output/
6
+ static/
7
+ model.py
8
+ requirements.txt
9
+ frontend/node_modules/
10
+ frontend/dist/
11
+ node_modules/
12
+ dist/
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build PWA and serve static (ONNX models pre-built in frontend/public/models)
2
+
3
+ FROM node:20-alpine AS frontend-build
4
+ WORKDIR /frontend
5
+ COPY frontend/package.json frontend/package-lock.json* ./
6
+ RUN npm ci
7
+ COPY frontend/ .
8
+ RUN npm run build
9
+
10
+ FROM python:3.10-slim
11
+ LABEL maintainer="NPI Pipe Count"
12
+ ENV PYTHONUNBUFFERED=1
13
+ WORKDIR /app
14
+ COPY requirements-server.txt .
15
+ RUN pip install --no-cache-dir -r requirements-server.txt
16
+ COPY main.py .
17
+ COPY --from=frontend-build /frontend/dist ./static
18
+ RUN useradd -m appuser && chown -R appuser:appuser /app
19
+ USER appuser
20
+ EXPOSE 7860
21
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
22
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/health')"
23
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
KNOWLEDGE.md ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pipe Counting Knowledge Base
2
+
3
+ > **v1.0 (2026)** — The app is now an **offline-first PWA** with in-browser ONNX inference (`frontend/`), diameter clustering, interactive correction, and client-side export. The Hugging Face Space serves static files only (`main.py`). Model export: `scripts/export_onnx.py`.
4
+
5
+ This document synthesizes key industry and research insights from CountThings (commercial leader) and Ivan Fenster's Medium article (award-winning academic/offline approach) with direct application notes for our local **Pipe Counting PWA (`pipecountapp`)** codebase.
6
+
7
+ ---
8
+
9
+ ## 1. Executive Summary & Core Concepts
10
+
11
+ Pipe counting is a critical computer vision task in industrial logistics, manufacturing, and metallurgy. The domain consists of two distinct paradigms:
12
+ 1. **Commercial SaaS / Guided Multi-Class Platforms (e.g., CountThings)**: Focuses on high-touch interactive correction, multi-layered "pipes-in-pipes" classification, and rigorous audit trails.
13
+ 2. **Offline-First High-Density Detection (e.g., Ivan Fenster / PipesCounting)**: Focuses on lightweight edge inference (TFLite/YOLO), synthetic dataset generation, and algorithmic post-processing to handle highly dense overlapping bundles.
14
+
15
+ Below is an in-depth breakdown of these two sources and how they can be used to advance our `pipecountapp` architecture.
16
+
17
+ ---
18
+
19
+ ## 2. CountThings: "Pipes in Pipes" Guide (ID: 466)
20
+
21
+ [CountThings](https://countthings.com/en/guides/0003) is the commercial standard for photographic counting. Their "Pipes in Pipes" counting template addresses the industry challenge of complex concentric/nested pipe bundles of varying diameters.
22
+
23
+ ### Key Workflows & Features
24
+ * **Multi-Class Classification by Size**: Enables detection and categorization of varying pipe diameters in a single photo (e.g., 75 mm, 110 mm, 180 mm, 250 mm).
25
+ * **Expected Quantity Verification**: Users can enter an "expected quantity" before running the count. The UI automatically highlights discrepancies between expected and detected values, acting as an automated QA/QC check.
26
+ * **Interactive Correction UI**:
27
+ * **Tag Selection**: Reclassify individual incorrectly detected sizes (e.g., if a 110 mm pipe is misidentified as a 180 mm pipe, select the target class and tap the pipe to correct it).
28
+ * **Area Selection**: Make bulk corrections across a custom drawn region of the image at once.
29
+ * **Tag Correction (Add/Delete)**: Users can manually tap to add a missing tag or delete a spurious detection.
30
+ * **Export Strategy**: Saves a result photo for *every individual pipe size* counted, ensuring traceability and visual proof.
31
+
32
+ ### Relevance to Our Codebase
33
+ * **Current State**: Our `main.py` relies on a single-class YOLOv5 model (`countmodel.pt`) that draws a sequential count indicator over each pipe end.
34
+ * **Future Enhancement**:
35
+ * If our model expands to support multiple classes (e.g., different diameter ranges), we can implement tag filtering.
36
+ * We can expose the `/detect/json` coordinates to a frontend layer to allow manual "Tag Correction" (tap to delete, tap to add, drag to resize) and sync those modifications back to our count tracking.
37
+
38
+ ---
39
+
40
+ ## 3. Ivan Fenster (Medium): Offline AI Tool for Metallurgy
41
+
42
+ [Ivan Fenster et al.](https://medium.com/@ivanfenster/developing-pipes-counting-how-to-build-an-offline-ai-tool-for-metalurgy-3b5d6df46007) (Letovo School) developed **PipesCounting**, an offline-first mobile app that placed 2nd in the International AI Junior Contest ("Metallurgy" category).
43
+
44
+ ### Technical Specifications
45
+ * **Architecture**: Fine-tuned YOLOv8, exported to **TensorFlow Lite (LiteRT)** for offline Android execution.
46
+ * **APK Optimization**: PyTorch was rejected as it inflated the APK size to 1.5 GB. Switching to TensorFlow Lite reduced the payload to **70 MB**.
47
+ * **Classes Detected**: Four primary industrial profiles:
48
+ 1. Round pipes
49
+ 2. Square pipes
50
+ 3. Angle bars (L-shaped)
51
+ 4. Channel bars (U-shaped)
52
+
53
+ ### Dataset & Labeling
54
+ * **Custom Dataset**: Round and square datasets were acquired from open-source repositories, but **angle and channel bars** lacked datasets. The team manually labeled **12,000 pipes** in CVAT.
55
+ * **Roboflow Dataset Link**: [PipesCounting Dataset on Roboflow](https://universe.roboflow.com/ignat/pipescounting_dataset-t7yey)
56
+ * **Augmentation**:
57
+ * *Flip*: Doubles dataset size.
58
+ * *Rotation (±15°)*: Helps with camera tilts on-site.
59
+ * *Brightness/Exposure*: Mimics variable lighting in production shops.
60
+ * *Blur*: Handles fast-moving or shaky mobile capture.
61
+ * *Mosaic*: Merges 4 frames to synthesize busy environments.
62
+ * **Synthetic Data Generation**:
63
+ * Production backgrounds were combined with cutoutends of real pipes using three stacking patterns: **No pattern** (randomly scattered), **Simple pattern** (rows, no nesting), and **Complex pattern** (nested).
64
+ * **Finding**: Surprisingly, synthetic data *did not* improve validation accuracy and occasionally degraded it. This was attributed to a lack of realism in the backgrounds and limited variation in pipe endpoints.
65
+
66
+ ### Algorithmic Highlights (Crucial for Dense Bundles)
67
+ 1. **The "Large Bundle Problem"**: Standard YOLO networks experience a steep drop-off in detection quality on very dense clusters (e.g., >200 pipes). Some objects stop registering altogether.
68
+ 2. **Overlapping Split Tiling Strategy**:
69
+ * Split the image into 4 quadrant tiles with a small overlap.
70
+ * Run inference on each quadrant independently.
71
+ * Combine results and resolve duplicates at overlapping boundaries. Duplicate bboxes are merged by evaluating center-to-edge distance and keeping the larger bounding box.
72
+ 3. **Outlier Filtering (Median Area Filter)**:
73
+ * In a bundle, physical pipes have uniform sizes. Spurious YOLO detections are often unusually small (random noise) or extremely large (merging multiple pipes).
74
+ * **Algorithm**: Compute the median area of all bounding boxes. Remove detections whose areas deviate significantly from this median.
75
+
76
+ ---
77
+
78
+ ## 4. Architectural Comparison & Optimization Plan
79
+
80
+ | Feature / Metric | `pipecountapp` (Our Codebase) | PipesCounting (Medium Study) | Actionable Upgrade for Our Codebase |
81
+ |:---|:---|:---|:---|
82
+ | **Model Version** | YOLOv5 (`countmodel.pt`) | YOLOv8 (`yolov8x.pt` to TFLite) | Keep YOLOv5 for compatibility, but optimize inference thread count dynamically based on resource limits. |
83
+ | **Inference Target** | CPU (Optimized via OpenMP threads) | Edge CPU (TFLite / LiteRT) | We can deploy OpenVINO or ONNX Runtime to further accelerate server-side CPU inference. |
84
+ | **Handling Large Bundles** | Resizes original to `MIN_IMAGE_HEIGHT=1500` and infers the full frame. | Quadrant tiling with overlaps. | **Feature Candidate**: Introduce an optional tiling preprocessor in `ImageProcessor` for ultra-high-resolution or dense images. |
85
+ | **Post-Processing Filtering** | `sort_detections_by_position` (custom grid-based row sorting) | Median Area Filter (Outlier removal) | **Feature Candidate**: Implement a `filter_outliers` method in `ImageProcessor` to drop boxes with area < 0.2x or > 3x the median box area. |
86
+ | **Deployment Mode** | Server-side API (FastAPI + Docker) | Client-side Offline (Kivy + Buildozer) | Keep API-first, but optimize image transfer overhead via configurable JPEG compression. |
87
+
88
+ ---
89
+
90
+ ## 5. Practical Code Implementations for Future Enhancement
91
+
92
+ ### A. Median Area Outlier Filter (Python / OpenCV)
93
+ To stabilize counts on noisy images, we can add this filter directly to our `ImageProcessor` class:
94
+
95
+ ```python
96
+ def filter_outliers(detections: List[Dict[str, Any]], lower_mult: float = 0.25, upper_mult: float = 4.0) -> List[Dict[str, Any]]:
97
+ """
98
+ Filters out spurious bboxes that are significantly smaller or larger
99
+ than the median pipe size in the bundle.
100
+ """
101
+ if not detections:
102
+ return []
103
+
104
+ # Calculate areas
105
+ areas = []
106
+ for d in detections:
107
+ w = d['xmax'] - d['xmin']
108
+ h = d['ymax'] - d['ymin']
109
+ areas.append(w * h)
110
+
111
+ median_area = np.median(areas)
112
+ filtered = []
113
+
114
+ for i, d in enumerate(detections):
115
+ area = areas[i]
116
+ # Keep only detections within the threshold scale of the median
117
+ if (median_area * lower_mult) <= area <= (median_area * upper_mult):
118
+ filtered.append(d)
119
+
120
+ return filtered
121
+ ```
122
+
123
+ ### B. Quadrant Tiling Preprocessor (Python)
124
+ For high-density pictures where YOLO misses pipes due to size ratios, we can process overlapping quadrants:
125
+
126
+ ```python
127
+ def tile_inference(image: np.ndarray, model, overlap_ratio: float = 0.1) -> List[Dict[str, Any]]:
128
+ """
129
+ Splits the image into 4 quadrants with overlap, infers each,
130
+ and applies custom NMS / Duplication resolution on the combined list.
131
+ """
132
+ h, w = image.shape[:2]
133
+ mid_y, mid_x = h // 2, w // 2
134
+ dy = int(mid_y * overlap_ratio)
135
+ dx = int(mid_x * overlap_ratio)
136
+
137
+ # Define bounding coordinates of 4 overlapping quadrants
138
+ quadrants = [
139
+ # Top-Left
140
+ (0, mid_y + dy, 0, mid_x + dx),
141
+ # Top-Right
142
+ (0, mid_y + dy, mid_x - dx, w),
143
+ # Bottom-Left
144
+ (mid_y - dy, h, 0, mid_x + dx),
145
+ # Bottom-Right
146
+ (mid_y - dy, h, mid_x - dx, w)
147
+ ]
148
+
149
+ all_detections = []
150
+ for ymin, ymax, xmin, xmax in quadrants:
151
+ crop = image[ymin:ymax, xmin:xmax]
152
+ results = model(crop)
153
+ dets = results.pandas().xyxy[0].to_dict('records')
154
+
155
+ # Translate coordinates back to full image coordinate space
156
+ for d in dets:
157
+ d['xmin'] += xmin
158
+ d['xmax'] += xmin
159
+ d['ymin'] += ymin
160
+ d['ymax'] += ymax
161
+ all_detections.append(d)
162
+
163
+ # Apply deduplication logic based on center proximity or standard NMS
164
+ return deduplicate_detections(all_detections)
165
+ ```
166
+
167
+ ---
168
+
169
+ ## 6. Resources & Citation
170
+ * CountThings Pipes-in-Pipes Guide: [https://countthings.com/en/guides/0003](https://countthings.com/en/guides/0003)
171
+ * Ivan Fenster Medium Article: [https://medium.com/@ivanfenster/developing-pipes-counting-how-to-build-an-offline-ai-tool-for-metalurgy-3b5d6df46007](https://medium.com/@ivanfenster/developing-pipes-counting-how-to-build-an-offline-ai-tool-for-metalurgy-3b5d6df46007)
172
+ * Roboflow Dataset: [https://universe.roboflow.com/ignat/pipescounting_dataset-t7yey](https://universe.roboflow.com/ignat/pipescounting_dataset-t7yey)
README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Pipe Count Dev
3
+ emoji: 🔧
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # Pipe Counting PWA (Offline-First)
12
+
13
+ Modern offline-first PWA for counting pipes with **in-browser ONNX inference**, diameter clustering, and interactive correction.
14
+
15
+ ## Features
16
+
17
+ - **Offline inference** — YOLOv5 model runs in the browser via ONNX Runtime Web (WebGPU / WASM)
18
+ - **Multi-diameter sorting** — clusters pipes by bounding-box size (no retraining)
19
+ - **Interactive correction** — add, delete, re-tag, and area-select pipes
20
+ - **Expected vs counted QA** — optional per-group expected quantity
21
+ - **Export** — annotated PNG, JSON, CSV (client-side)
22
+ - **Bilingual** — Thai / English UI
23
+ - **Fast deploy** — tiny Docker image (no PyTorch at runtime)
24
+
25
+ ## Architecture
26
+
27
+ ```
28
+ Browser PWA → ONNX Runtime Web → YOLOv5 countmodel.onnx
29
+ ↓
30
+ Diameter clustering + user corrections + export
31
+ ↑
32
+ HF Space serves static files only (main.py)
33
+ ```
34
+
35
+ ## Local development
36
+
37
+ ### Frontend only
38
+ ```bash
39
+ cd frontend
40
+ npm install
41
+ npm run dev
42
+ ```
43
+
44
+ ### Full stack (built PWA + API)
45
+ ```bash
46
+ cd frontend && npm run build
47
+ # copy dist + models to static/
48
+ cd ..
49
+ pip install -r requirements-server.txt
50
+ uvicorn main:app --host 0.0.0.0 --port 7860
51
+ ```
52
+
53
+ ### Export ONNX model (one-time / CI)
54
+ ```bash
55
+ pip install -r requirements-export.txt
56
+ pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
57
+ git clone --depth 1 https://github.com/ultralytics/yolov5.git
58
+ python scripts/export_onnx.py
59
+ ```
60
+
61
+ ## API Endpoints
62
+
63
+ | Endpoint | Method | Description |
64
+ |----------|--------|-------------|
65
+ | `/` | GET | PWA shell |
66
+ | `/health` | GET | Health check |
67
+
68
+ ## Hugging Face Spaces
69
+
70
+ - SDK: Docker
71
+ - Port: 7860
72
+ - Hardware: Free CPU is sufficient (inference runs on client devices)
73
+ - Build uses multi-stage Dockerfile: export ONNX → build PWA → serve static
74
+
75
+ ## Configuration
76
+
77
+ | Variable | Default | Description |
78
+ |----------|---------|-------------|
79
+ | (none required) | — | Inference is client-side |
80
+
81
+ Legacy server inference endpoints (`/detectImage`, `/detect/json`) were removed in v1.0.0.
countmodel.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e50a34760e185a97276d1c4db01ef2c39a607ea4af7225ee31df6ef7094b1bc
3
+ size 14921049
credit.png ADDED
frontend/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
frontend/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + TypeScript + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
9
+
10
+ ## React Compiler
11
+
12
+ The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
13
+
14
+ ## Expanding the ESLint configuration
15
+
16
+ If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
17
+
18
+ ```js
19
+ export default defineConfig([
20
+ globalIgnores(['dist']),
21
+ {
22
+ files: ['**/*.{ts,tsx}'],
23
+ extends: [
24
+ // Other configs...
25
+
26
+ // Remove tseslint.configs.recommended and replace with this
27
+ tseslint.configs.recommendedTypeChecked,
28
+ // Alternatively, use this for stricter rules
29
+ tseslint.configs.strictTypeChecked,
30
+ // Optionally, add this for stylistic rules
31
+ tseslint.configs.stylisticTypeChecked,
32
+
33
+ // Other configs...
34
+ ],
35
+ languageOptions: {
36
+ parserOptions: {
37
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
38
+ tsconfigRootDir: import.meta.dirname,
39
+ },
40
+ // other options...
41
+ },
42
+ },
43
+ ])
44
+ ```
45
+
46
+ You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
47
+
48
+ ```js
49
+ // eslint.config.js
50
+ import reactX from 'eslint-plugin-react-x'
51
+ import reactDom from 'eslint-plugin-react-dom'
52
+
53
+ export default defineConfig([
54
+ globalIgnores(['dist']),
55
+ {
56
+ files: ['**/*.{ts,tsx}'],
57
+ extends: [
58
+ // Other configs...
59
+ // Enable lint rules for React
60
+ reactX.configs['recommended-typescript'],
61
+ // Enable lint rules for React DOM
62
+ reactDom.configs.recommended,
63
+ ],
64
+ languageOptions: {
65
+ parserOptions: {
66
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
67
+ tsconfigRootDir: import.meta.dirname,
68
+ },
69
+ // other options...
70
+ },
71
+ },
72
+ ])
73
+ ```
frontend/eslint.config.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import tseslint from 'typescript-eslint'
6
+ import { defineConfig, globalIgnores } from 'eslint/config'
7
+
8
+ export default defineConfig([
9
+ globalIgnores(['dist']),
10
+ {
11
+ files: ['**/*.{ts,tsx}'],
12
+ extends: [
13
+ js.configs.recommended,
14
+ tseslint.configs.recommended,
15
+ reactHooks.configs.flat.recommended,
16
+ reactRefresh.configs.vite,
17
+ ],
18
+ languageOptions: {
19
+ globals: globals.browser,
20
+ },
21
+ },
22
+ ])
frontend/index.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="th">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <meta name="theme-color" content="#0f172a" />
7
+ <meta name="apple-mobile-web-app-capable" content="yes" />
8
+ <title>NPI Pipe Count</title>
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ <script type="module" src="/src/main.tsx"></script>
13
+ </body>
14
+ </html>
frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
frontend/package.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "pipecount-frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "clsx": "^2.1.1",
14
+ "lucide-react": "^1.18.0",
15
+ "onnxruntime-web": "^1.26.0",
16
+ "react": "^19.2.6",
17
+ "react-dom": "^19.2.6",
18
+ "tailwind-merge": "^3.6.0",
19
+ "vite-plugin-pwa": "^1.3.0",
20
+ "workbox-window": "^7.4.1"
21
+ },
22
+ "devDependencies": {
23
+ "@eslint/js": "^10.0.1",
24
+ "@tailwindcss/vite": "^4.3.1",
25
+ "@types/node": "^24.12.3",
26
+ "@types/react": "^19.2.14",
27
+ "@types/react-dom": "^19.2.3",
28
+ "@vitejs/plugin-react": "^6.0.1",
29
+ "eslint": "^10.3.0",
30
+ "eslint-plugin-react-hooks": "^7.1.1",
31
+ "eslint-plugin-react-refresh": "^0.5.2",
32
+ "globals": "^17.6.0",
33
+ "tailwindcss": "^4.3.1",
34
+ "typescript": "~6.0.2",
35
+ "typescript-eslint": "^8.59.2",
36
+ "vite": "^8.0.12"
37
+ }
38
+ }
frontend/public/favicon.svg ADDED
frontend/public/icon.svg ADDED
frontend/public/icons.svg ADDED
frontend/public/models/countmodel-640-int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:402f69e674662ecc2bcbf023b4767712d48302eed3faac9046315e1463bac938
3
+ size 7812279
frontend/public/models/countmodel-640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:739ba0f8621d471d895bd95fb0b17f2a4fed191ff42c70007f726c5fe18f1321
3
+ size 29451943
frontend/public/models/countmodel-int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c4846b1934470542480fea8f4d76d22fda512d3e7a385e2ade1725b9a098d26
3
+ size 8441421
frontend/public/models/countmodel.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52d3ec2d0f1da1a3aa0d07396ef6a75966b36bac91a65274e5a458b53858dcf2
3
+ size 30081085
frontend/src/App.css ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .counter {
2
+ font-size: 16px;
3
+ padding: 5px 10px;
4
+ border-radius: 5px;
5
+ color: var(--accent);
6
+ background: var(--accent-bg);
7
+ border: 2px solid transparent;
8
+ transition: border-color 0.3s;
9
+ margin-bottom: 24px;
10
+
11
+ &:hover {
12
+ border-color: var(--accent-border);
13
+ }
14
+ &:focus-visible {
15
+ outline: 2px solid var(--accent);
16
+ outline-offset: 2px;
17
+ }
18
+ }
19
+
20
+ .hero {
21
+ position: relative;
22
+
23
+ .base,
24
+ .framework,
25
+ .vite {
26
+ inset-inline: 0;
27
+ margin: 0 auto;
28
+ }
29
+
30
+ .base {
31
+ width: 170px;
32
+ position: relative;
33
+ z-index: 0;
34
+ }
35
+
36
+ .framework,
37
+ .vite {
38
+ position: absolute;
39
+ }
40
+
41
+ .framework {
42
+ z-index: 1;
43
+ top: 34px;
44
+ height: 28px;
45
+ transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
46
+ scale(1.4);
47
+ }
48
+
49
+ .vite {
50
+ z-index: 0;
51
+ top: 107px;
52
+ height: 26px;
53
+ width: auto;
54
+ transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
55
+ scale(0.8);
56
+ }
57
+ }
58
+
59
+ #center {
60
+ display: flex;
61
+ flex-direction: column;
62
+ gap: 25px;
63
+ place-content: center;
64
+ place-items: center;
65
+ flex-grow: 1;
66
+
67
+ @media (max-width: 1024px) {
68
+ padding: 32px 20px 24px;
69
+ gap: 18px;
70
+ }
71
+ }
72
+
73
+ #next-steps {
74
+ display: flex;
75
+ border-top: 1px solid var(--border);
76
+ text-align: left;
77
+
78
+ & > div {
79
+ flex: 1 1 0;
80
+ padding: 32px;
81
+ @media (max-width: 1024px) {
82
+ padding: 24px 20px;
83
+ }
84
+ }
85
+
86
+ .icon {
87
+ margin-bottom: 16px;
88
+ width: 22px;
89
+ height: 22px;
90
+ }
91
+
92
+ @media (max-width: 1024px) {
93
+ flex-direction: column;
94
+ text-align: center;
95
+ }
96
+ }
97
+
98
+ #docs {
99
+ border-right: 1px solid var(--border);
100
+
101
+ @media (max-width: 1024px) {
102
+ border-right: none;
103
+ border-bottom: 1px solid var(--border);
104
+ }
105
+ }
106
+
107
+ #next-steps ul {
108
+ list-style: none;
109
+ padding: 0;
110
+ display: flex;
111
+ gap: 8px;
112
+ margin: 32px 0 0;
113
+
114
+ .logo {
115
+ height: 18px;
116
+ }
117
+
118
+ a {
119
+ color: var(--text-h);
120
+ font-size: 16px;
121
+ border-radius: 6px;
122
+ background: var(--social-bg);
123
+ display: flex;
124
+ padding: 6px 12px;
125
+ align-items: center;
126
+ gap: 8px;
127
+ text-decoration: none;
128
+ transition: box-shadow 0.3s;
129
+
130
+ &:hover {
131
+ box-shadow: var(--shadow);
132
+ }
133
+ .button-icon {
134
+ height: 18px;
135
+ width: 18px;
136
+ }
137
+ }
138
+
139
+ @media (max-width: 1024px) {
140
+ margin-top: 20px;
141
+ flex-wrap: wrap;
142
+ justify-content: center;
143
+
144
+ li {
145
+ flex: 1 1 calc(50% - 8px);
146
+ }
147
+
148
+ a {
149
+ width: 100%;
150
+ justify-content: center;
151
+ box-sizing: border-box;
152
+ }
153
+ }
154
+ }
155
+
156
+ #spacer {
157
+ height: 88px;
158
+ border-top: 1px solid var(--border);
159
+ @media (max-width: 1024px) {
160
+ height: 48px;
161
+ }
162
+ }
163
+
164
+ .ticks {
165
+ position: relative;
166
+ width: 100%;
167
+
168
+ &::before,
169
+ &::after {
170
+ content: '';
171
+ position: absolute;
172
+ top: -4.5px;
173
+ border: 5px solid transparent;
174
+ }
175
+
176
+ &::before {
177
+ left: 0;
178
+ border-left-color: var(--border);
179
+ }
180
+ &::after {
181
+ right: 0;
182
+ border-right-color: var(--border);
183
+ }
184
+ }
frontend/src/App.tsx ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import { Camera, ImagePlus, Loader2 } from 'lucide-react'
3
+ import { assignDiameterGroups, countByGroup } from './lib/clustering'
4
+ import { exportCanvasPng, exportCsv, exportJson } from './lib/export'
5
+ import { getActiveBackend, loadModel, runDetection } from './lib/inference'
6
+ import { t } from './lib/i18n'
7
+ import type { Detection, DiameterGroup, Lang, ToolMode } from './lib/types'
8
+ import { DetectionCanvas } from './components/DetectionCanvas'
9
+ import { GroupPanel } from './components/GroupPanel'
10
+
11
+ export default function App() {
12
+ const [lang, setLang] = useState<Lang>('th')
13
+ const [image, setImage] = useState<HTMLImageElement | null>(null)
14
+ const [detections, setDetections] = useState<Detection[]>([])
15
+ const [groups, setGroups] = useState<DiameterGroup[]>([])
16
+ const [tool, setTool] = useState<ToolMode>('view')
17
+ const [selectedGroupId, setSelectedGroupId] = useState(0)
18
+ const [groupCount, setGroupCount] = useState<number | 'auto'>('auto')
19
+ const [status, setStatus] = useState('')
20
+ const [busy, setBusy] = useState(false)
21
+ const [modelReady, setModelReady] = useState(false)
22
+ const [useTiling, setUseTiling] = useState(false)
23
+ const [exportCanvas, setExportCanvas] = useState<HTMLCanvasElement | null>(null)
24
+ const fileRef = useRef<HTMLInputElement>(null)
25
+ const cameraRef = useRef<HTMLInputElement>(null)
26
+
27
+ useEffect(() => {
28
+ loadModel(setStatus)
29
+ .then(() => setModelReady(true))
30
+ .catch((err: unknown) => setStatus(String(err)))
31
+ }, [])
32
+
33
+ const counts = countByGroup(detections, groups)
34
+
35
+ const loadFile = (file: File) => {
36
+ const url = URL.createObjectURL(file)
37
+ const img = new Image()
38
+ img.onload = () => {
39
+ setImage(img)
40
+ setDetections([])
41
+ setGroups([])
42
+ URL.revokeObjectURL(url)
43
+ }
44
+ img.src = url
45
+ }
46
+
47
+ const runCount = async () => {
48
+ if (!image) {
49
+ return
50
+ }
51
+ setBusy(true)
52
+ setStatus(t(lang, 'processing'))
53
+ try {
54
+ const dets = await runDetection(image, { useTiling, onProgress: setStatus })
55
+ const clustered = assignDiameterGroups(dets, groupCount, lang)
56
+ setDetections(clustered.detections)
57
+ setGroups(clustered.groups)
58
+ setSelectedGroupId(0)
59
+ setStatus(`Done (${getActiveBackend()})`)
60
+ } catch (err) {
61
+ setStatus(String(err))
62
+ } finally {
63
+ setBusy(false)
64
+ }
65
+ }
66
+
67
+ const recluster = () => {
68
+ const clustered = assignDiameterGroups(detections, groupCount, lang)
69
+ setDetections(clustered.detections)
70
+ setGroups(clustered.groups)
71
+ }
72
+
73
+ const handleExpectedChange = (groupId: number, value: number | undefined) => {
74
+ setGroups((prev) => prev.map((g) => (g.id === groupId ? { ...g, expected: value } : g)))
75
+ }
76
+
77
+ const tools: { id: ToolMode; label: string }[] = [
78
+ { id: 'view', label: t(lang, 'toolView') },
79
+ { id: 'delete', label: t(lang, 'toolDelete') },
80
+ { id: 'add', label: t(lang, 'toolAdd') },
81
+ { id: 'reassign', label: t(lang, 'toolReassign') },
82
+ { id: 'area', label: t(lang, 'toolArea') },
83
+ ]
84
+
85
+ return (
86
+ <div className="mx-auto flex min-h-dvh max-w-6xl flex-col gap-4 p-4 pb-8">
87
+ <header className="flex flex-wrap items-center justify-between gap-3">
88
+ <div>
89
+ <h1 className="text-2xl font-bold text-white">{t(lang, 'title')}</h1>
90
+ <p className="text-sm text-slate-400">{t(lang, 'subtitle')}</p>
91
+ <p className="text-xs text-slate-500">{t(lang, 'company')}</p>
92
+ </div>
93
+ <div className="flex gap-2">
94
+ <button
95
+ type="button"
96
+ className="rounded-lg bg-slate-800 px-3 py-1 text-sm"
97
+ onClick={() => setLang(lang === 'th' ? 'en' : 'th')}
98
+ >
99
+ {lang === 'th' ? 'EN' : 'TH'}
100
+ </button>
101
+ </div>
102
+ </header>
103
+
104
+ <div className="flex flex-wrap gap-2">
105
+ <button
106
+ type="button"
107
+ className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 font-medium"
108
+ onClick={() => cameraRef.current?.click()}
109
+ >
110
+ <Camera size={18} /> {t(lang, 'takePhoto')}
111
+ </button>
112
+ <button
113
+ type="button"
114
+ className="flex items-center gap-2 rounded-lg bg-slate-700 px-4 py-2"
115
+ onClick={() => fileRef.current?.click()}
116
+ >
117
+ <ImagePlus size={18} /> {t(lang, 'chooseFile')}
118
+ </button>
119
+ <button
120
+ type="button"
121
+ disabled={!image || busy || !modelReady}
122
+ className="flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 font-semibold disabled:opacity-50"
123
+ onClick={runCount}
124
+ >
125
+ {busy ? <Loader2 className="animate-spin" size={18} /> : null}
126
+ {t(lang, 'count')}
127
+ </button>
128
+ </div>
129
+
130
+ <input
131
+ ref={fileRef}
132
+ type="file"
133
+ accept="image/*"
134
+ className="hidden"
135
+ onChange={(e) => e.target.files?.[0] && loadFile(e.target.files[0])}
136
+ />
137
+ <input
138
+ ref={cameraRef}
139
+ type="file"
140
+ accept="image/*"
141
+ capture="environment"
142
+ className="hidden"
143
+ onChange={(e) => e.target.files?.[0] && loadFile(e.target.files[0])}
144
+ />
145
+
146
+ <div className="grid gap-4 lg:grid-cols-[1fr_280px]">
147
+ <div className="space-y-3">
148
+ {!image ? (
149
+ <div className="flex h-64 items-center justify-center rounded-xl border border-dashed border-slate-600 text-slate-400">
150
+ {t(lang, 'noImage')}
151
+ </div>
152
+ ) : (
153
+ <DetectionCanvas
154
+ image={image}
155
+ detections={detections}
156
+ groups={groups}
157
+ tool={tool}
158
+ selectedGroupId={selectedGroupId}
159
+ onUpdate={setDetections}
160
+ onCanvasReady={setExportCanvas}
161
+ />
162
+ )}
163
+ {status && <p className="text-sm text-slate-400">{status}</p>}
164
+ </div>
165
+
166
+ <aside className="space-y-4">
167
+ <div className="rounded-xl border border-slate-700 bg-slate-900/50 p-4">
168
+ <div className="text-3xl font-bold">{detections.length}</div>
169
+ <div className="text-sm text-slate-400">{t(lang, 'total')}</div>
170
+ </div>
171
+
172
+ <div className="space-y-2 rounded-xl border border-slate-700 bg-slate-900/50 p-4">
173
+ <label className="text-sm text-slate-300">{t(lang, 'groupCount')}</label>
174
+ <div className="flex flex-wrap gap-2">
175
+ <button
176
+ type="button"
177
+ className={`rounded px-3 py-1 text-sm ${groupCount === 'auto' ? 'bg-blue-600' : 'bg-slate-800'}`}
178
+ onClick={() => setGroupCount('auto')}
179
+ >
180
+ {t(lang, 'auto')}
181
+ </button>
182
+ {[1, 2, 3, 4, 5, 6].map((n) => (
183
+ <button
184
+ key={n}
185
+ type="button"
186
+ className={`rounded px-3 py-1 text-sm ${groupCount === n ? 'bg-blue-600' : 'bg-slate-800'}`}
187
+ onClick={() => setGroupCount(n)}
188
+ >
189
+ {n}
190
+ </button>
191
+ ))}
192
+ <button type="button" className="rounded bg-slate-700 px-3 py-1 text-sm" onClick={recluster}>
193
+ Apply
194
+ </button>
195
+ </div>
196
+ <label className="flex items-center gap-2 text-sm text-slate-300">
197
+ <input type="checkbox" checked={useTiling} onChange={(e) => setUseTiling(e.target.checked)} />
198
+ {t(lang, 'highAccuracy')}
199
+ </label>
200
+ </div>
201
+
202
+ {groups.length > 0 && (
203
+ <GroupPanel
204
+ lang={lang}
205
+ groups={groups}
206
+ counts={counts}
207
+ selectedGroupId={selectedGroupId}
208
+ onSelectGroup={setSelectedGroupId}
209
+ onExpectedChange={handleExpectedChange}
210
+ />
211
+ )}
212
+
213
+ <div className="space-y-2">
214
+ <p className="text-xs text-slate-400">{t(lang, 'selectGroup')}</p>
215
+ <div className="flex flex-wrap gap-1">
216
+ {tools.map((toolItem) => (
217
+ <button
218
+ key={toolItem.id}
219
+ type="button"
220
+ className={`rounded px-2 py-1 text-xs ${tool === toolItem.id ? 'bg-white text-slate-900' : 'bg-slate-800'}`}
221
+ onClick={() => setTool(toolItem.id)}
222
+ >
223
+ {toolItem.label}
224
+ </button>
225
+ ))}
226
+ </div>
227
+ </div>
228
+
229
+ <div className="flex flex-wrap gap-2">
230
+ <button
231
+ type="button"
232
+ className="rounded bg-slate-700 px-3 py-2 text-sm"
233
+ disabled={!exportCanvas}
234
+ onClick={() => exportCanvas && exportCanvasPng(exportCanvas)}
235
+ >
236
+ {t(lang, 'exportPng')}
237
+ </button>
238
+ <button
239
+ type="button"
240
+ className="rounded bg-slate-700 px-3 py-2 text-sm"
241
+ disabled={detections.length === 0}
242
+ onClick={() => exportJson(detections, groups, counts)}
243
+ >
244
+ {t(lang, 'exportJson')}
245
+ </button>
246
+ <button
247
+ type="button"
248
+ className="rounded bg-slate-700 px-3 py-2 text-sm"
249
+ disabled={detections.length === 0}
250
+ onClick={() => exportCsv(detections, groups)}
251
+ >
252
+ {t(lang, 'exportCsv')}
253
+ </button>
254
+ </div>
255
+ </aside>
256
+ </div>
257
+ </div>
258
+ )
259
+ }
frontend/src/assets/hero.png ADDED
frontend/src/assets/react.svg ADDED
frontend/src/assets/vite.svg ADDED
frontend/src/components/DetectionCanvas.tsx ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef } from 'react'
2
+ import type { Detection, DiameterGroup, ToolMode } from '../lib/types'
3
+
4
+ interface Props {
5
+ image: HTMLImageElement | null
6
+ detections: Detection[]
7
+ groups: DiameterGroup[]
8
+ tool: ToolMode
9
+ selectedGroupId: number
10
+ onUpdate: (detections: Detection[]) => void
11
+ onCanvasReady?: (canvas: HTMLCanvasElement | null) => void
12
+ }
13
+
14
+ export function DetectionCanvas({
15
+ image,
16
+ detections,
17
+ groups,
18
+ tool,
19
+ selectedGroupId,
20
+ onUpdate,
21
+ onCanvasReady,
22
+ }: Props) {
23
+ const canvasRef = useRef<HTMLCanvasElement>(null)
24
+ const dragRef = useRef<{ x: number; y: number } | null>(null)
25
+ const areaRef = useRef<{ x1: number; y1: number; x2: number; y2: number } | null>(null)
26
+
27
+ useEffect(() => {
28
+ onCanvasReady?.(canvasRef.current)
29
+ }, [onCanvasReady, image, detections])
30
+
31
+ useEffect(() => {
32
+ const canvas = canvasRef.current
33
+ if (!canvas || !image) {
34
+ return
35
+ }
36
+ const ctx = canvas.getContext('2d')
37
+ if (!ctx) {
38
+ return
39
+ }
40
+
41
+ const maxW = canvas.parentElement?.clientWidth ?? image.naturalWidth
42
+ const scale = Math.min(1, maxW / image.naturalWidth)
43
+ canvas.width = Math.round(image.naturalWidth * scale)
44
+ canvas.height = Math.round(image.naturalHeight * scale)
45
+ ctx.clearRect(0, 0, canvas.width, canvas.height)
46
+ ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
47
+
48
+ detections.forEach((d, idx) => {
49
+ const group = groups.find((g) => g.id === d.groupId) ?? groups[0]
50
+ const color = group?.color ?? '#ef4444'
51
+ const x = d.xmin * scale
52
+ const y = d.ymin * scale
53
+ const w = (d.xmax - d.xmin) * scale
54
+ const h = (d.ymax - d.ymin) * scale
55
+ const cx = x + w / 2
56
+ const cy = y + h / 2
57
+ const r = Math.max(10, Math.min(w, h) / 2)
58
+
59
+ ctx.beginPath()
60
+ ctx.arc(cx, cy, r, 0, Math.PI * 2)
61
+ ctx.strokeStyle = color
62
+ ctx.lineWidth = 3
63
+ ctx.stroke()
64
+
65
+ ctx.fillStyle = color
66
+ ctx.font = 'bold 12px sans-serif'
67
+ ctx.textAlign = 'center'
68
+ ctx.textBaseline = 'middle'
69
+ ctx.fillText(String(idx + 1), cx, cy)
70
+ })
71
+
72
+ const area = areaRef.current
73
+ if (area) {
74
+ ctx.strokeStyle = '#fff'
75
+ ctx.setLineDash([6, 4])
76
+ ctx.strokeRect(
77
+ area.x1 * scale,
78
+ area.y1 * scale,
79
+ (area.x2 - area.x1) * scale,
80
+ (area.y2 - area.y1) * scale,
81
+ )
82
+ ctx.setLineDash([])
83
+ }
84
+ }, [image, detections, groups])
85
+
86
+ const toImageCoords = (clientX: number, clientY: number) => {
87
+ const canvas = canvasRef.current!
88
+ const rect = canvas.getBoundingClientRect()
89
+ const scale = image!.naturalWidth / canvas.width
90
+ return {
91
+ x: (clientX - rect.left) * scale,
92
+ y: (clientY - rect.top) * scale,
93
+ displayScale: canvas.width / image!.naturalWidth,
94
+ }
95
+ }
96
+
97
+ const findHit = (x: number, y: number) => {
98
+ for (let i = detections.length - 1; i >= 0; i--) {
99
+ const d = detections[i]
100
+ if (x >= d.xmin && x <= d.xmax && y >= d.ymin && y <= d.ymax) {
101
+ return i
102
+ }
103
+ }
104
+ return -1
105
+ }
106
+
107
+ const handlePointerDown = (e: React.PointerEvent) => {
108
+ if (!image) {
109
+ return
110
+ }
111
+ const { x, y } = toImageCoords(e.clientX, e.clientY)
112
+ if (tool === 'area') {
113
+ dragRef.current = { x, y }
114
+ areaRef.current = { x1: x, y1: y, x2: x, y2: y }
115
+ return
116
+ }
117
+ const hit = findHit(x, y)
118
+ if (tool === 'delete' && hit >= 0) {
119
+ onUpdate(detections.filter((_, i) => i !== hit))
120
+ return
121
+ }
122
+ if (tool === 'reassign' && hit >= 0) {
123
+ onUpdate(
124
+ detections.map((d, i) => (i === hit ? { ...d, groupId: selectedGroupId, manual: true } : d)),
125
+ )
126
+ return
127
+ }
128
+ if (tool === 'add') {
129
+ const size = 24
130
+ onUpdate([
131
+ ...detections,
132
+ {
133
+ id: `manual-${Date.now()}`,
134
+ xmin: x - size / 2,
135
+ ymin: y - size / 2,
136
+ xmax: x + size / 2,
137
+ ymax: y + size / 2,
138
+ confidence: 1,
139
+ groupId: selectedGroupId,
140
+ manual: true,
141
+ },
142
+ ])
143
+ }
144
+ }
145
+
146
+ const handlePointerMove = (e: React.PointerEvent) => {
147
+ if (!dragRef.current || tool !== 'area') {
148
+ return
149
+ }
150
+ const { x, y } = toImageCoords(e.clientX, e.clientY)
151
+ areaRef.current = {
152
+ x1: Math.min(dragRef.current.x, x),
153
+ y1: Math.min(dragRef.current.y, y),
154
+ x2: Math.max(dragRef.current.x, x),
155
+ y2: Math.max(dragRef.current.y, y),
156
+ }
157
+ onUpdate([...detections])
158
+ }
159
+
160
+ const handlePointerUp = () => {
161
+ if (tool === 'area' && areaRef.current) {
162
+ const a = areaRef.current
163
+ onUpdate(
164
+ detections.map((d) => {
165
+ const cx = (d.xmin + d.xmax) / 2
166
+ const cy = (d.ymin + d.ymax) / 2
167
+ if (cx >= a.x1 && cx <= a.x2 && cy >= a.y1 && cy <= a.y2) {
168
+ return { ...d, groupId: selectedGroupId, manual: true }
169
+ }
170
+ return d
171
+ }),
172
+ )
173
+ }
174
+ dragRef.current = null
175
+ areaRef.current = null
176
+ onUpdate([...detections])
177
+ }
178
+
179
+ if (!image) {
180
+ return null
181
+ }
182
+
183
+ return (
184
+ <canvas
185
+ ref={canvasRef}
186
+ className="w-full rounded-xl border border-slate-700 bg-black touch-none"
187
+ onPointerDown={handlePointerDown}
188
+ onPointerMove={handlePointerMove}
189
+ onPointerUp={handlePointerUp}
190
+ onPointerLeave={handlePointerUp}
191
+ />
192
+ )
193
+ }
frontend/src/components/GroupPanel.tsx ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { DiameterGroup } from '../lib/types'
2
+ import { t } from '../lib/i18n'
3
+ import type { Lang } from '../lib/types'
4
+
5
+ interface Props {
6
+ lang: Lang
7
+ groups: DiameterGroup[]
8
+ counts: Record<number, number>
9
+ selectedGroupId: number
10
+ onSelectGroup: (id: number) => void
11
+ onExpectedChange: (groupId: number, value: number | undefined) => void
12
+ }
13
+
14
+ export function GroupPanel({
15
+ lang,
16
+ groups,
17
+ counts,
18
+ selectedGroupId,
19
+ onSelectGroup,
20
+ onExpectedChange,
21
+ }: Props) {
22
+ return (
23
+ <div className="space-y-2">
24
+ <h3 className="text-sm font-semibold text-slate-300">{t(lang, 'groups')}</h3>
25
+ {groups.map((g) => {
26
+ const count = counts[g.id] ?? 0
27
+ const mismatch = g.expected !== undefined && g.expected !== count
28
+ return (
29
+ <button
30
+ key={g.id}
31
+ type="button"
32
+ onClick={() => onSelectGroup(g.id)}
33
+ className={`w-full rounded-lg border p-3 text-left transition ${
34
+ selectedGroupId === g.id
35
+ ? 'border-white bg-slate-800'
36
+ : 'border-slate-700 bg-slate-900/60 hover:border-slate-500'
37
+ }`}
38
+ >
39
+ <div className="flex items-center gap-2">
40
+ <span className="h-3 w-3 rounded-full" style={{ background: g.color }} />
41
+ <span className="font-medium">{g.label}</span>
42
+ <span className="ml-auto text-lg font-bold">{count}</span>
43
+ </div>
44
+ <div className="mt-2 flex items-center gap-2 text-xs text-slate-400">
45
+ <label htmlFor={`exp-${g.id}`}>{t(lang, 'expected')}:</label>
46
+ <input
47
+ id={`exp-${g.id}`}
48
+ type="number"
49
+ min={0}
50
+ className="w-16 rounded bg-slate-800 px-2 py-1 text-white"
51
+ value={g.expected ?? ''}
52
+ onChange={(e) => {
53
+ const v = e.target.value
54
+ onExpectedChange(g.id, v === '' ? undefined : Number(v))
55
+ }}
56
+ onClick={(e) => e.stopPropagation()}
57
+ />
58
+ {mismatch && (
59
+ <span className="text-amber-400">{t(lang, 'mismatch')}</span>
60
+ )}
61
+ </div>
62
+ </button>
63
+ )
64
+ })}
65
+ </div>
66
+ )
67
+ }
frontend/src/index.css ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import 'tailwindcss';
2
+
3
+ :root {
4
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
5
+ color: #f8fafc;
6
+ background: #0f172a;
7
+ }
8
+
9
+ body {
10
+ margin: 0;
11
+ min-height: 100dvh;
12
+ background: radial-gradient(circle at top, #1e293b, #0f172a 55%);
13
+ }
14
+
15
+ #root {
16
+ min-height: 100dvh;
17
+ }
18
+
19
+ button:disabled {
20
+ opacity: 0.5;
21
+ cursor: not-allowed;
22
+ }
frontend/src/lib/clustering.ts ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GROUP_COLORS } from './constants'
2
+ import type { Detection, DiameterGroup } from './types'
3
+
4
+ function diameterOf(d: Detection): number {
5
+ return Math.min(d.xmax - d.xmin, d.ymax - d.ymin)
6
+ }
7
+
8
+ function kMeans1D(values: number[], k: number, iterations = 20): number[] {
9
+ if (values.length === 0 || k <= 0) {
10
+ return []
11
+ }
12
+ const sorted = [...values].sort((a, b) => a - b)
13
+ const centroids = Array.from({ length: k }, (_, i) => {
14
+ const idx = Math.floor((i + 0.5) * (sorted.length / k))
15
+ return sorted[Math.min(idx, sorted.length - 1)]
16
+ })
17
+
18
+ for (let iter = 0; iter < iterations; iter++) {
19
+ const groups: number[][] = Array.from({ length: k }, () => [])
20
+ for (const v of values) {
21
+ let best = 0
22
+ let bestDist = Infinity
23
+ for (let c = 0; c < k; c++) {
24
+ const dist = Math.abs(v - centroids[c])
25
+ if (dist < bestDist) {
26
+ bestDist = dist
27
+ best = c
28
+ }
29
+ }
30
+ groups[best].push(v)
31
+ }
32
+ for (let c = 0; c < k; c++) {
33
+ if (groups[c].length > 0) {
34
+ centroids[c] = groups[c].reduce((a, b) => a + b, 0) / groups[c].length
35
+ }
36
+ }
37
+ }
38
+ return centroids.sort((a, b) => a - b)
39
+ }
40
+
41
+ function autoK(values: number[]): number {
42
+ if (values.length < 4) {
43
+ return 1
44
+ }
45
+ const sorted = [...values].sort((a, b) => a - b)
46
+ const gaps: number[] = []
47
+ for (let i = 1; i < sorted.length; i++) {
48
+ gaps.push(sorted[i] - sorted[i - 1])
49
+ }
50
+ const medianGap = gaps.sort((a, b) => a - b)[Math.floor(gaps.length / 2)] || 1
51
+ const bigGaps = gaps.filter((g) => g > medianGap * 2.5)
52
+ return Math.min(6, Math.max(1, bigGaps.length + 1))
53
+ }
54
+
55
+ export function buildGroups(k: number, lang: 'en' | 'th'): DiameterGroup[] {
56
+ return Array.from({ length: k }, (_, i) => ({
57
+ id: i,
58
+ label: lang === 'th' ? `กลุ่ม ${i + 1}` : `Group ${i + 1}`,
59
+ color: GROUP_COLORS[i % GROUP_COLORS.length],
60
+ }))
61
+ }
62
+
63
+ export function assignDiameterGroups(
64
+ detections: Detection[],
65
+ groupCount: number | 'auto',
66
+ lang: 'en' | 'th',
67
+ ): { detections: Detection[]; groups: DiameterGroup[] } {
68
+ if (detections.length === 0) {
69
+ return { detections: [], groups: buildGroups(1, lang) }
70
+ }
71
+
72
+ const diameters = detections.map(diameterOf)
73
+ const k = groupCount === 'auto' ? autoK(diameters) : Math.max(1, Math.min(6, groupCount))
74
+ const centroids = kMeans1D(diameters, k)
75
+ const groups = buildGroups(k, lang).map((g, i) => ({
76
+ ...g,
77
+ label: lang === 'th' ? `เส้นผ่านศูนย์กลาง ~${Math.round(centroids[i] || 0)}px` : `~${Math.round(centroids[i] || 0)}px`,
78
+ }))
79
+
80
+ const assigned = detections.map((d) => {
81
+ const dia = diameterOf(d)
82
+ let best = 0
83
+ let bestDist = Infinity
84
+ for (let i = 0; i < centroids.length; i++) {
85
+ const dist = Math.abs(dia - centroids[i])
86
+ if (dist < bestDist) {
87
+ bestDist = dist
88
+ best = i
89
+ }
90
+ }
91
+ return { ...d, groupId: best }
92
+ })
93
+
94
+ return { detections: assigned, groups }
95
+ }
96
+
97
+ export function countByGroup(detections: Detection[], groups: DiameterGroup[]): Record<number, number> {
98
+ const counts: Record<number, number> = {}
99
+ for (const g of groups) {
100
+ counts[g.id] = 0
101
+ }
102
+ for (const d of detections) {
103
+ counts[d.groupId] = (counts[d.groupId] ?? 0) + 1
104
+ }
105
+ return counts
106
+ }
frontend/src/lib/constants.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const MODEL_URL = '/models/countmodel.onnx'
2
+ export const MODEL_640_URL = '/models/countmodel-640.onnx'
3
+ export const MODEL_INT8_URL = '/models/countmodel-int8.onnx'
4
+ export const INFERENCE_SIZE = 1024
5
+ export const INFERENCE_SIZE_SMALL = 640
6
+ export const CONFIDENCE_THRESHOLD = 0.6
7
+ export const IOU_THRESHOLD = 0.45
8
+ export const MAX_DETECTIONS = 4000
9
+
10
+ export const GROUP_COLORS = [
11
+ '#ef4444',
12
+ '#3b82f6',
13
+ '#22c55e',
14
+ '#eab308',
15
+ '#a855f7',
16
+ '#f97316',
17
+ ]
frontend/src/lib/export.ts ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Detection, DiameterGroup } from './types'
2
+
3
+ export function exportJson(
4
+ detections: Detection[],
5
+ groups: DiameterGroup[],
6
+ counts: Record<number, number>,
7
+ ): void {
8
+ const payload = {
9
+ total: detections.length,
10
+ groups: groups.map((g) => ({
11
+ id: g.id,
12
+ label: g.label,
13
+ count: counts[g.id] ?? 0,
14
+ expected: g.expected ?? null,
15
+ })),
16
+ detections: detections.map((d, i) => ({
17
+ id: i + 1,
18
+ groupId: d.groupId,
19
+ confidence: d.confidence,
20
+ xmin: Math.round(d.xmin),
21
+ ymin: Math.round(d.ymin),
22
+ xmax: Math.round(d.xmax),
23
+ ymax: Math.round(d.ymax),
24
+ manual: d.manual ?? false,
25
+ })),
26
+ exportedAt: new Date().toISOString(),
27
+ }
28
+ downloadBlob(JSON.stringify(payload, null, 2), 'pipe-count.json', 'application/json')
29
+ }
30
+
31
+ export function exportCsv(
32
+ detections: Detection[],
33
+ groups: DiameterGroup[],
34
+ ): void {
35
+ const groupMap = Object.fromEntries(groups.map((g) => [g.id, g.label]))
36
+ const lines = ['id,group,group_label,xmin,ymin,xmax,ymax,confidence,manual']
37
+ detections.forEach((d, i) => {
38
+ lines.push(
39
+ [
40
+ i + 1,
41
+ d.groupId,
42
+ `"${groupMap[d.groupId] ?? ''}"`,
43
+ Math.round(d.xmin),
44
+ Math.round(d.ymin),
45
+ Math.round(d.xmax),
46
+ Math.round(d.ymax),
47
+ d.confidence.toFixed(3),
48
+ d.manual ? 1 : 0,
49
+ ].join(','),
50
+ )
51
+ })
52
+ downloadBlob(lines.join('\n'), 'pipe-count.csv', 'text/csv')
53
+ }
54
+
55
+ export function exportCanvasPng(canvas: HTMLCanvasElement): void {
56
+ canvas.toBlob((blob) => {
57
+ if (!blob) {
58
+ return
59
+ }
60
+ const url = URL.createObjectURL(blob)
61
+ const a = document.createElement('a')
62
+ a.href = url
63
+ a.download = 'pipe-count-result.png'
64
+ a.click()
65
+ URL.revokeObjectURL(url)
66
+ })
67
+ }
68
+
69
+ function downloadBlob(content: string, filename: string, type: string): void {
70
+ const blob = new Blob([content], { type })
71
+ const url = URL.createObjectURL(blob)
72
+ const a = document.createElement('a')
73
+ a.href = url
74
+ a.download = filename
75
+ a.click()
76
+ URL.revokeObjectURL(url)
77
+ }
frontend/src/lib/i18n.ts ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Lang } from './types'
2
+
3
+ const messages = {
4
+ en: {
5
+ title: 'NPI Pipe Count',
6
+ subtitle: 'Offline AI pipe counting with diameter sorting',
7
+ takePhoto: 'Take Photo',
8
+ chooseFile: 'Choose Image',
9
+ count: 'Count Pipes',
10
+ loadingModel: 'Loading model...',
11
+ processing: 'Processing...',
12
+ total: 'Total',
13
+ groups: 'Diameter Groups',
14
+ groupCount: 'Groups',
15
+ auto: 'Auto',
16
+ expected: 'Expected',
17
+ toolView: 'View',
18
+ toolDelete: 'Delete',
19
+ toolAdd: 'Add',
20
+ toolReassign: 'Re-tag',
21
+ toolArea: 'Area select',
22
+ exportPng: 'Export PNG',
23
+ exportJson: 'Export JSON',
24
+ exportCsv: 'Export CSV',
25
+ highAccuracy: 'High accuracy (4-tile)',
26
+ filterOutliers: 'Filter outliers',
27
+ mismatch: 'Mismatch',
28
+ selectGroup: 'Select target group',
29
+ noImage: 'Upload or capture a pipe bundle photo to begin.',
30
+ company: 'Nawaplastic Industry Co., Ltd.',
31
+ },
32
+ th: {
33
+ title: 'NPI นับท่อ',
34
+ subtitle: 'นับท่อออฟไลน์ พร้อมจัดกลุ่มตามเส้นผ่านศูนย์กลาง',
35
+ takePhoto: 'ถ่ายภาพ',
36
+ chooseFile: 'เลือกรูป',
37
+ count: 'นับท่อ',
38
+ loadingModel: 'กำลังโหลดโมเดล...',
39
+ processing: 'กำลังประมวลผล...',
40
+ total: 'รวม',
41
+ groups: 'กลุ่มเส้นผ่านศูนย์กลาง',
42
+ groupCount: 'จำนวนกลุ่ม',
43
+ auto: 'อัตโนมัติ',
44
+ expected: 'คาดหวัง',
45
+ toolView: 'ดู',
46
+ toolDelete: 'ลบ',
47
+ toolAdd: 'เพิ่ม',
48
+ toolReassign: 'เปลี่ยนกลุ่ม',
49
+ toolArea: 'เลือกพื้นที่',
50
+ exportPng: 'ส่งออก PNG',
51
+ exportJson: 'ส่งออก JSON',
52
+ exportCsv: 'ส่งออก CSV',
53
+ highAccuracy: 'ความแม่นยำสูง (4 ส่วน)',
54
+ filterOutliers: 'กรองค่าผิดปกติ',
55
+ mismatch: 'ไม่ตรง',
56
+ selectGroup: 'เลือกกลุ่มเป้าหมาย',
57
+ noImage: 'อัปโหลดหรือถ่ายภาพมัดท่อเพื่อเริ่มต้น',
58
+ company: 'บริษัท นวพลาสติก อุตสาหกรรม จำกัด',
59
+ },
60
+ } as const
61
+
62
+ export function t(lang: Lang, key: keyof (typeof messages)['en']): string {
63
+ return messages[lang][key]
64
+ }
frontend/src/lib/inference.ts ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as ort from 'onnxruntime-web'
2
+ import { CONFIDENCE_THRESHOLD, IOU_THRESHOLD, MAX_DETECTIONS, MODEL_640_URL, MODEL_URL } from './constants'
3
+ import { selectModelForImage } from './modelSelect'
4
+ import { filterOutliers, nonMaxSuppression } from './nms'
5
+ import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
6
+ import type { Detection, LetterboxMeta } from './types'
7
+
8
+ ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'
9
+
10
+ let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
11
+ let activeBackend = 'loading'
12
+
13
+ async function createSession(modelUrl: string): Promise<ort.InferenceSession> {
14
+ const backends: Array<{ name: string; providers: ort.InferenceSession.SessionOptions['executionProviders'] }> = [
15
+ { name: 'webgpu', providers: ['webgpu', 'wasm'] },
16
+ { name: 'wasm', providers: ['wasm'] },
17
+ ]
18
+
19
+ for (const backend of backends) {
20
+ try {
21
+ const session = await ort.InferenceSession.create(modelUrl, {
22
+ executionProviders: backend.providers,
23
+ graphOptimizationLevel: 'all',
24
+ })
25
+ activeBackend = backend.name
26
+ return session
27
+ } catch {
28
+ continue
29
+ }
30
+ }
31
+ throw new Error('Failed to initialize ONNX Runtime')
32
+ }
33
+
34
+ function getSession(modelUrl: string): Promise<ort.InferenceSession> {
35
+ let cached = sessionCache.get(modelUrl)
36
+ if (!cached) {
37
+ cached = createSession(modelUrl)
38
+ sessionCache.set(modelUrl, cached)
39
+ }
40
+ return cached
41
+ }
42
+
43
+ export function getActiveBackend(): string {
44
+ return activeBackend
45
+ }
46
+
47
+ export async function loadModel(onProgress?: (msg: string) => void): Promise<void> {
48
+ onProgress?.('Loading models...')
49
+ await Promise.all([getSession(MODEL_URL), getSession(MODEL_640_URL)])
50
+ onProgress?.(`Models ready (${activeBackend})`)
51
+ }
52
+
53
+ export function decodeOutput(
54
+ output: Float32Array,
55
+ meta: LetterboxMeta,
56
+ imageW: number,
57
+ imageH: number,
58
+ confThreshold = CONFIDENCE_THRESHOLD,
59
+ applyOutlierFilter = false,
60
+ ): Detection[] {
61
+ const rows = output.length / 6
62
+ const raw = []
63
+
64
+ for (let i = 0; i < rows; i++) {
65
+ const base = i * 6
66
+ const cx = output[base]
67
+ const cy = output[base + 1]
68
+ const w = output[base + 2]
69
+ const h = output[base + 3]
70
+ const obj = output[base + 4]
71
+ const cls = output[base + 5]
72
+ const confidence = obj * cls
73
+ if (confidence < confThreshold) {
74
+ continue
75
+ }
76
+ const box = mapBoxToOriginal(cx, cy, w, h, meta)
77
+ box.xmin = Math.max(0, Math.min(imageW, box.xmin))
78
+ box.ymin = Math.max(0, Math.min(imageH, box.ymin))
79
+ box.xmax = Math.max(0, Math.min(imageW, box.xmax))
80
+ box.ymax = Math.max(0, Math.min(imageH, box.ymax))
81
+ if (box.xmax <= box.xmin || box.ymax <= box.ymin) {
82
+ continue
83
+ }
84
+ raw.push({ ...box, confidence })
85
+ }
86
+
87
+ let filtered = nonMaxSuppression(raw, IOU_THRESHOLD, MAX_DETECTIONS)
88
+ if (applyOutlierFilter) {
89
+ filtered = filterOutliers(filtered)
90
+ }
91
+ return filtered.map((d, idx) => ({
92
+ ...d,
93
+ id: `det-${idx}-${Date.now()}`,
94
+ groupId: 0,
95
+ confidence: d.confidence,
96
+ }))
97
+ }
98
+
99
+ export async function runDetection(
100
+ image: HTMLImageElement,
101
+ options?: { useTiling?: boolean; filterOutliers?: boolean; onProgress?: (msg: string) => void },
102
+ ): Promise<Detection[]> {
103
+ await loadModel(options?.onProgress)
104
+ const { modelUrl, inferenceSize } = selectModelForImage(
105
+ image.naturalWidth,
106
+ image.naturalHeight,
107
+ )
108
+ const session = await getSession(modelUrl)
109
+ const start = performance.now()
110
+
111
+ if (options?.useTiling) {
112
+ return runTiledDetection(image, session, inferenceSize, options)
113
+ }
114
+
115
+ const { canvas, meta } = letterboxCanvas(image, inferenceSize)
116
+ const tensor = canvasToTensor(canvas, inferenceSize)
117
+ const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
118
+ const results = await session.run({ images: input })
119
+ const output = results.output.data as Float32Array
120
+ const detections = decodeOutput(
121
+ output,
122
+ meta,
123
+ image.naturalWidth,
124
+ image.naturalHeight,
125
+ CONFIDENCE_THRESHOLD,
126
+ options?.filterOutliers ?? false,
127
+ )
128
+ options?.onProgress?.(`Detected ${detections.length} pipes in ${Math.round(performance.now() - start)}ms`)
129
+ return detections
130
+ }
131
+
132
+ async function runTiledDetection(
133
+ image: HTMLImageElement,
134
+ session: ort.InferenceSession,
135
+ inferenceSize: number,
136
+ options?: { filterOutliers?: boolean; onProgress?: (msg: string) => void },
137
+ ): Promise<Detection[]> {
138
+ const onProgress = options?.onProgress
139
+ const w = image.naturalWidth
140
+ const h = image.naturalHeight
141
+ const midX = w / 2
142
+ const midY = h / 2
143
+ const overlap = 0.1
144
+ const dx = midX * overlap
145
+ const dy = midY * overlap
146
+ const tiles = [
147
+ { x: 0, y: 0, w: midX + dx, h: midY + dy },
148
+ { x: midX - dx, y: 0, w: w - midX + dx, h: midY + dy },
149
+ { x: 0, y: midY - dy, w: midX + dx, h: h - midY + dy },
150
+ { x: midX - dx, y: midY - dy, w: w - midX + dx, h: h - midY + dy },
151
+ ]
152
+
153
+ const all: Detection[] = []
154
+ for (let i = 0; i < tiles.length; i++) {
155
+ onProgress?.(`Tiling ${i + 1}/4...`)
156
+ const tile = tiles[i]
157
+ const tileCanvas = document.createElement('canvas')
158
+ tileCanvas.width = tile.w
159
+ tileCanvas.height = tile.h
160
+ const ctx = tileCanvas.getContext('2d')!
161
+ ctx.drawImage(image, tile.x, tile.y, tile.w, tile.h, 0, 0, tile.w, tile.h)
162
+
163
+ const img = new Image()
164
+ img.src = tileCanvas.toDataURL()
165
+ await new Promise<void>((resolve) => {
166
+ img.onload = () => resolve()
167
+ })
168
+
169
+ const { canvas, meta } = letterboxCanvas(img, inferenceSize)
170
+ const tensor = canvasToTensor(canvas, inferenceSize)
171
+ const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
172
+ const results = await session.run({ images: input })
173
+ const output = results.output.data as Float32Array
174
+ const dets = decodeOutput(
175
+ output,
176
+ meta,
177
+ tile.w,
178
+ tile.h,
179
+ CONFIDENCE_THRESHOLD,
180
+ options?.filterOutliers ?? false,
181
+ )
182
+ for (const d of dets) {
183
+ all.push({
184
+ ...d,
185
+ xmin: d.xmin + tile.x,
186
+ ymin: d.ymin + tile.y,
187
+ xmax: d.xmax + tile.x,
188
+ ymax: d.ymax + tile.y,
189
+ id: `tile-${i}-${d.id}`,
190
+ groupId: 0,
191
+ })
192
+ }
193
+ }
194
+
195
+ const merged = nonMaxSuppression(all, IOU_THRESHOLD, MAX_DETECTIONS).map((d, idx) => ({
196
+ ...d,
197
+ id: `merged-${idx}`,
198
+ groupId: 0,
199
+ }))
200
+ onProgress?.(`Tiled detection: ${merged.length} pipes`)
201
+ return merged
202
+ }
frontend/src/lib/modelSelect.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ INFERENCE_SIZE,
3
+ INFERENCE_SIZE_SMALL,
4
+ MODEL_640_URL,
5
+ MODEL_URL,
6
+ } from './constants'
7
+
8
+ export function selectModelForImage(width: number, height: number): {
9
+ modelUrl: string
10
+ inferenceSize: number
11
+ } {
12
+ // Large portrait images over-detect at 1024; use 640 instead.
13
+ const isLargePortrait = height > width * 1.3 || Math.max(width, height) > 2400
14
+ if (isLargePortrait) {
15
+ return { modelUrl: MODEL_640_URL, inferenceSize: INFERENCE_SIZE_SMALL }
16
+ }
17
+ return { modelUrl: MODEL_URL, inferenceSize: INFERENCE_SIZE }
18
+ }
frontend/src/lib/nms.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { BBox } from './types'
2
+
3
+ export interface RawDetection extends BBox {
4
+ confidence: number
5
+ }
6
+
7
+ function iou(a: BBox, b: BBox): number {
8
+ const x1 = Math.max(a.xmin, b.xmin)
9
+ const y1 = Math.max(a.ymin, b.ymin)
10
+ const x2 = Math.min(a.xmax, b.xmax)
11
+ const y2 = Math.min(a.ymax, b.ymax)
12
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1)
13
+ const areaA = (a.xmax - a.xmin) * (a.ymax - a.ymin)
14
+ const areaB = (b.xmax - b.xmin) * (b.ymax - b.ymin)
15
+ return inter / (areaA + areaB - inter + 1e-6)
16
+ }
17
+
18
+ export function nonMaxSuppression(
19
+ detections: RawDetection[],
20
+ iouThreshold: number,
21
+ maxDet: number,
22
+ ): RawDetection[] {
23
+ const sorted = [...detections].sort((a, b) => b.confidence - a.confidence)
24
+ const kept: RawDetection[] = []
25
+
26
+ for (const det of sorted) {
27
+ let skip = false
28
+ for (const k of kept) {
29
+ if (iou(det, k) > iouThreshold) {
30
+ skip = true
31
+ break
32
+ }
33
+ }
34
+ if (!skip) {
35
+ kept.push(det)
36
+ }
37
+ if (kept.length >= maxDet) {
38
+ break
39
+ }
40
+ }
41
+ return kept
42
+ }
43
+
44
+ export function filterOutliers(
45
+ detections: RawDetection[],
46
+ lowerMult = 0.25,
47
+ upperMult = 4,
48
+ ): RawDetection[] {
49
+ if (detections.length < 3) {
50
+ return detections
51
+ }
52
+ const areas = detections.map((d) => (d.xmax - d.xmin) * (d.ymax - d.ymin))
53
+ const sorted = [...areas].sort((a, b) => a - b)
54
+ const median = sorted[Math.floor(sorted.length / 2)]
55
+ return detections.filter((_, i) => {
56
+ const area = areas[i]
57
+ return area >= median * lowerMult && area <= median * upperMult
58
+ })
59
+ }
frontend/src/lib/preprocess.ts ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { LetterboxMeta } from './types'
2
+ import { INFERENCE_SIZE } from './constants'
3
+
4
+ export function letterboxCanvas(
5
+ image: HTMLImageElement | HTMLCanvasElement,
6
+ size = INFERENCE_SIZE,
7
+ ): { canvas: HTMLCanvasElement; meta: LetterboxMeta } {
8
+ const canvas = document.createElement('canvas')
9
+ canvas.width = size
10
+ canvas.height = size
11
+ const ctx = canvas.getContext('2d')
12
+ if (!ctx) {
13
+ throw new Error('Canvas 2D not available')
14
+ }
15
+
16
+ const srcW = 'naturalWidth' in image ? image.naturalWidth : image.width
17
+ const srcH = 'naturalHeight' in image ? image.naturalHeight : image.height
18
+ const scale = Math.min(size / srcW, size / srcH)
19
+ const newW = Math.round(srcW * scale)
20
+ const newH = Math.round(srcH * scale)
21
+ const padX = Math.floor((size - newW) / 2)
22
+ const padY = Math.floor((size - newH) / 2)
23
+
24
+ ctx.fillStyle = '#727272'
25
+ ctx.fillRect(0, 0, size, size)
26
+ ctx.drawImage(image, padX, padY, newW, newH)
27
+
28
+ return {
29
+ canvas,
30
+ meta: { scale, padX, padY, inputSize: size },
31
+ }
32
+ }
33
+
34
+ export function canvasToTensor(canvas: HTMLCanvasElement, size = INFERENCE_SIZE): Float32Array {
35
+ const ctx = canvas.getContext('2d')
36
+ if (!ctx) {
37
+ throw new Error('Canvas 2D not available')
38
+ }
39
+ const { data } = ctx.getImageData(0, 0, size, size)
40
+ const tensor = new Float32Array(3 * size * size)
41
+ let p = 0
42
+ for (let i = 0; i < data.length; i += 4) {
43
+ tensor[p++] = data[i] / 255
44
+ tensor[p++] = data[i + 1] / 255
45
+ tensor[p++] = data[i + 2] / 255
46
+ }
47
+
48
+ const chw = new Float32Array(3 * size * size)
49
+ const plane = size * size
50
+ for (let i = 0; i < plane; i++) {
51
+ chw[i] = tensor[i * 3]
52
+ chw[plane + i] = tensor[i * 3 + 1]
53
+ chw[2 * plane + i] = tensor[i * 3 + 2]
54
+ }
55
+ return chw
56
+ }
57
+
58
+ export function mapBoxToOriginal(
59
+ cx: number,
60
+ cy: number,
61
+ w: number,
62
+ h: number,
63
+ meta: LetterboxMeta,
64
+ ): { xmin: number; ymin: number; xmax: number; ymax: number } {
65
+ const x1 = (cx - w / 2 - meta.padX) / meta.scale
66
+ const y1 = (cy - h / 2 - meta.padY) / meta.scale
67
+ const x2 = (cx + w / 2 - meta.padX) / meta.scale
68
+ const y2 = (cy + h / 2 - meta.padY) / meta.scale
69
+ return { xmin: x1, ymin: y1, xmax: x2, ymax: y2 }
70
+ }
frontend/src/lib/types.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface BBox {
2
+ xmin: number
3
+ ymin: number
4
+ xmax: number
5
+ ymax: number
6
+ }
7
+
8
+ export interface Detection extends BBox {
9
+ id: string
10
+ confidence: number
11
+ groupId: number
12
+ manual?: boolean
13
+ }
14
+
15
+ export interface DiameterGroup {
16
+ id: number
17
+ label: string
18
+ color: string
19
+ expected?: number
20
+ }
21
+
22
+ export type ToolMode = 'view' | 'delete' | 'add' | 'reassign' | 'area'
23
+
24
+ export type Lang = 'en' | 'th'
25
+
26
+ export interface LetterboxMeta {
27
+ scale: number
28
+ padX: number
29
+ padY: number
30
+ inputSize: number
31
+ }
frontend/src/main.tsx ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import { registerSW } from 'virtual:pwa-register'
4
+ import './index.css'
5
+ import App from './App.tsx'
6
+
7
+ registerSW({ immediate: true })
8
+
9
+ createRoot(document.getElementById('root')!).render(
10
+ <StrictMode>
11
+ <App />
12
+ </StrictMode>,
13
+ )
frontend/src/vite-env.d.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ /// <reference types="vite/client" />
2
+ /// <reference types="vite-plugin-pwa/client" />
frontend/tsconfig.app.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
4
+ "target": "es2023",
5
+ "lib": ["ES2023", "DOM"],
6
+ "module": "esnext",
7
+ "types": ["vite/client"],
8
+ "skipLibCheck": true,
9
+
10
+ /* Bundler mode */
11
+ "moduleResolution": "bundler",
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+ "jsx": "react-jsx",
17
+
18
+ /* Linting */
19
+ "noUnusedLocals": true,
20
+ "noUnusedParameters": true,
21
+ "erasableSyntaxOnly": true,
22
+ "noFallthroughCasesInSwitch": true
23
+ },
24
+ "include": ["src"]
25
+ }
frontend/tsconfig.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [],
3
+ "references": [
4
+ { "path": "./tsconfig.app.json" },
5
+ { "path": "./tsconfig.node.json" }
6
+ ]
7
+ }
frontend/tsconfig.node.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
4
+ "target": "es2023",
5
+ "lib": ["ES2023"],
6
+ "module": "esnext",
7
+ "types": ["node"],
8
+ "skipLibCheck": true,
9
+
10
+ /* Bundler mode */
11
+ "moduleResolution": "bundler",
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+
17
+ /* Linting */
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "erasableSyntaxOnly": true,
21
+ "noFallthroughCasesInSwitch": true
22
+ },
23
+ "include": ["vite.config.ts"]
24
+ }
frontend/vite.config.ts ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+ import tailwindcss from '@tailwindcss/vite'
4
+ import { VitePWA } from 'vite-plugin-pwa'
5
+
6
+ export default defineConfig({
7
+ plugins: [
8
+ react(),
9
+ tailwindcss(),
10
+ VitePWA({
11
+ registerType: 'autoUpdate',
12
+ includeAssets: ['models/countmodel.onnx', 'models/countmodel-640.onnx', 'models/countmodel-int8.onnx'],
13
+ manifest: {
14
+ name: 'NPI Pipe Count',
15
+ short_name: 'Pipe Count',
16
+ description: 'Offline pipe counting with diameter sorting',
17
+ theme_color: '#0f172a',
18
+ background_color: '#0f172a',
19
+ display: 'standalone',
20
+ orientation: 'portrait',
21
+ start_url: '/',
22
+ icons: [
23
+ {
24
+ src: '/icon.svg',
25
+ sizes: '512x512',
26
+ type: 'image/svg+xml',
27
+ purpose: 'any maskable',
28
+ },
29
+ ],
30
+ },
31
+ workbox: {
32
+ globPatterns: ['**/*.{js,css,html,ico,png,svg,onnx,wasm}'],
33
+ maximumFileSizeToCacheInBytes: 30 * 1024 * 1024,
34
+ },
35
+ }),
36
+ ],
37
+ server: {
38
+ headers: {
39
+ 'Cross-Origin-Opener-Policy': 'same-origin',
40
+ 'Cross-Origin-Embedder-Policy': 'require-corp',
41
+ },
42
+ },
43
+ preview: {
44
+ headers: {
45
+ 'Cross-Origin-Opener-Policy': 'same-origin',
46
+ 'Cross-Origin-Embedder-Policy': 'require-corp',
47
+ },
48
+ },
49
+ build: {
50
+ outDir: 'dist',
51
+ sourcemap: false,
52
+ },
53
+ })
main.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from fastapi import FastAPI, HTTPException
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from fastapi.responses import FileResponse, JSONResponse
6
+ from starlette.middleware.base import BaseHTTPMiddleware
7
+ from starlette.requests import Request
8
+
9
+ APP_VERSION = "1.0.0"
10
+ STATIC_PATH = Path(__file__).resolve().parent / "static"
11
+
12
+
13
+ class CrossOriginIsolationMiddleware(BaseHTTPMiddleware):
14
+ async def dispatch(self, request: Request, call_next):
15
+ response = await call_next(request)
16
+ response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
17
+ response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
18
+ return response
19
+
20
+
21
+ app = FastAPI(
22
+ title="NPI Pipe Count PWA",
23
+ description="Offline-first pipe counting PWA with in-browser ONNX inference",
24
+ version=APP_VERSION,
25
+ )
26
+
27
+ app.add_middleware(CrossOriginIsolationMiddleware)
28
+ app.add_middleware(
29
+ CORSMiddleware,
30
+ allow_origins=["*"],
31
+ allow_methods=["*"],
32
+ allow_headers=["*"],
33
+ )
34
+
35
+
36
+ @app.get("/health")
37
+ async def health_check():
38
+ model_path = STATIC_PATH / "models" / "countmodel.onnx"
39
+ return JSONResponse(
40
+ {
41
+ "status": "ok",
42
+ "version": APP_VERSION,
43
+ "mode": "static-pwa",
44
+ "model_present": model_path.is_file(),
45
+ }
46
+ )
47
+
48
+
49
+ @app.get("/{filename:path}")
50
+ async def serve_file(filename: str):
51
+ if not filename:
52
+ filename = "index.html"
53
+ file_path = (STATIC_PATH / filename).resolve()
54
+ if not str(file_path).startswith(str(STATIC_PATH.resolve())):
55
+ raise HTTPException(status_code=403, detail="Forbidden")
56
+ if file_path.is_file():
57
+ return FileResponse(file_path)
58
+ # SPA fallback
59
+ index = STATIC_PATH / "index.html"
60
+ if index.is_file():
61
+ return FileResponse(index)
62
+ raise HTTPException(status_code=404, detail="File not found")
requirements-export.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=1.8.0
2
+ torchvision>=0.9.0
3
+ onnx>=1.17.0
4
+ onnxruntime>=1.19.0
5
+ onnxsim>=0.4.36
6
+ onnxscript>=0.1.0
7
+ ultralytics>=8.0.147
8
+ opencv-python-headless>=4.8.0
9
+ numpy>=1.22.0
10
+ PyYAML>=5.3.1
11
+ pandas>=1.1.4
12
+ tqdm>=4.64.0
13
+ seaborn>=0.11.0
requirements-server.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Slim server requirements (no torch)
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.32.0
4
+ python-multipart>=0.0.9
scripts/build-static.bat ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ cd /d %~dp0frontend
3
+ call npm run build
4
+ cd /d %~dp0
5
+ if exist static rmdir /s /q static
6
+ mkdir static
7
+ xcopy /E /I /Y frontend\dist\* static\
8
+ xcopy /E /I /Y frontend\public\models static\models\
9
+ copy /Y frontend\public\icon.svg static\icon.svg
10
+ echo Build copied to static/
scripts/export_onnx.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export countmodel.pt to ONNX for browser inference."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import onnx
10
+ import onnxruntime as ort
11
+ import torch
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+
16
+
17
+ def load_model(weights: Path, conf: float = 0.6) -> torch.nn.Module:
18
+ wrapped = torch.hub.load(
19
+ str(ROOT / "yolov5"),
20
+ "custom",
21
+ path=str(weights),
22
+ source="local",
23
+ force_reload=False,
24
+ )
25
+ model = wrapped.model if hasattr(wrapped, "model") else wrapped
26
+ model.conf = conf
27
+ model.max_det = 4000
28
+ model.eval()
29
+ model.cpu()
30
+ return model
31
+
32
+
33
+ def export_onnx(model: torch.nn.Module, output: Path, imgsz: int = 640, opset: int = 12) -> None:
34
+ dummy = torch.zeros(1, 3, imgsz, imgsz)
35
+ output.parent.mkdir(parents=True, exist_ok=True)
36
+ torch.onnx.export(
37
+ model,
38
+ dummy,
39
+ str(output),
40
+ opset_version=opset,
41
+ input_names=["images"],
42
+ output_names=["output"],
43
+ dynamic_axes={"images": {0: "batch"}, "output": {0: "batch"}},
44
+ )
45
+ # simplify if onnxsim available
46
+ try:
47
+ import onnxsim
48
+
49
+ model_onnx = onnx.load(str(output))
50
+ model_simp, check = onnxsim.simplify(model_onnx)
51
+ if check:
52
+ onnx.save(model_simp, str(output))
53
+ print(f"Simplified ONNX saved to {output}")
54
+ else:
55
+ print("ONNX simplify check failed; keeping original export")
56
+ except Exception as exc:
57
+ print(f"ONNX simplify skipped: {exc}")
58
+
59
+
60
+ def quantize_int8(fp32_path: Path, int8_path: Path) -> None:
61
+ from onnxruntime.quantization import QuantType, quantize_dynamic
62
+
63
+ quantize_dynamic(
64
+ str(fp32_path),
65
+ str(int8_path),
66
+ weight_type=QuantType.QUInt8,
67
+ )
68
+ print(f"INT8 model saved to {int8_path}")
69
+
70
+
71
+ def parity_check(model: torch.nn.Module, onnx_path: Path, imgsz: int = 640) -> None:
72
+ dummy = np.random.randint(0, 255, (imgsz, imgsz, 3), dtype=np.uint8)
73
+ img = dummy.astype(np.float32) / 255.0
74
+ img_chw = np.transpose(img, (2, 0, 1))
75
+ tensor = torch.from_numpy(img_chw).unsqueeze(0)
76
+
77
+ with torch.inference_mode():
78
+ pt_out = model(tensor)[0].numpy()
79
+
80
+ sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
81
+ ort_out = sess.run(None, {"images": tensor.numpy()})[0]
82
+
83
+ diff = np.abs(pt_out - ort_out).max()
84
+ print(f"Parity max abs diff: {diff:.6f}")
85
+ if diff > 0.05:
86
+ print("WARNING: ONNX output differs significantly from PyTorch")
87
+
88
+
89
+ def main() -> None:
90
+ parser = argparse.ArgumentParser()
91
+ parser.add_argument("--weights", type=Path, default=ROOT / "countmodel.pt")
92
+ parser.add_argument("--out-dir", type=Path, default=ROOT / "frontend" / "public" / "models")
93
+ parser.add_argument("--imgsz", type=int, default=1024)
94
+ args = parser.parse_args()
95
+
96
+ model = load_model(args.weights)
97
+ fp32_path = args.out_dir / "countmodel.onnx"
98
+ int8_path = args.out_dir / "countmodel-int8.onnx"
99
+
100
+ export_onnx(model, fp32_path, imgsz=args.imgsz)
101
+ parity_check(model, fp32_path, imgsz=args.imgsz)
102
+ quantize_int8(fp32_path, int8_path)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
scripts/test_samples.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test ONNX pipe-count model on sample images (matches browser pipeline)."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import onnxruntime as ort
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ MODEL_PATH = ROOT / "static" / "models" / "countmodel.onnx"
14
+ INFERENCE_SIZE = 1024
15
+ CONF_THRESHOLD = 0.6
16
+ IOU_THRESHOLD = 0.45
17
+ MAX_DET = 4000
18
+
19
+
20
+ def letterbox(img: np.ndarray, size: int = INFERENCE_SIZE):
21
+ h, w = img.shape[:2]
22
+ scale = min(size / w, size / h)
23
+ new_w, new_h = int(round(w * scale)), int(round(h * scale))
24
+ pad_x = (size - new_w) // 2
25
+ pad_y = (size - new_h) // 2
26
+ out = np.full((size, size, 3), 114, dtype=np.uint8)
27
+ resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
28
+ out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
29
+ tensor = out[:, :, ::-1].astype(np.float32) / 255.0 # BGR->RGB
30
+ chw = np.transpose(tensor, (2, 0, 1))[None, ...]
31
+ meta = {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
32
+ return chw, meta
33
+
34
+
35
+ def iou(a, b):
36
+ x1 = max(a[0], b[0])
37
+ y1 = max(a[1], b[1])
38
+ x2 = min(a[2], b[2])
39
+ y2 = min(a[3], b[3])
40
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
41
+ area_a = (a[2] - a[0]) * (a[3] - a[1])
42
+ area_b = (b[2] - b[0]) * (b[3] - b[1])
43
+ return inter / (area_a + area_b - inter + 1e-6)
44
+
45
+
46
+ def nms(boxes, scores, iou_thres=IOU_THRESHOLD, max_det=MAX_DET):
47
+ order = np.argsort(scores)[::-1]
48
+ keep = []
49
+ while order.size > 0 and len(keep) < max_det:
50
+ i = order[0]
51
+ keep.append(i)
52
+ if order.size == 1:
53
+ break
54
+ rest = order[1:]
55
+ ious = np.array([iou(boxes[i], boxes[j]) for j in rest])
56
+ order = rest[ious <= iou_thres]
57
+ return keep
58
+
59
+
60
+ def filter_outliers(boxes):
61
+ if len(boxes) < 3:
62
+ return list(range(len(boxes)))
63
+ areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
64
+ median = float(np.median(areas))
65
+ return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
66
+
67
+
68
+ def decode(output: np.ndarray, meta: dict, img_w: int, img_h: int, use_outliers: bool = False):
69
+ boxes, scores = [], []
70
+ for row in output.reshape(-1, 6):
71
+ cx, cy, w, h, obj, cls = row
72
+ conf = float(obj * cls)
73
+ if conf < CONF_THRESHOLD:
74
+ continue
75
+ x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"]
76
+ y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"]
77
+ x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"]
78
+ y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"]
79
+ x1, y1 = max(0, x1), max(0, y1)
80
+ x2, y2 = min(img_w, x2), min(img_h, y2)
81
+ if x2 <= x1 or y2 <= y1:
82
+ continue
83
+ boxes.append([x1, y1, x2, y2])
84
+ scores.append(conf)
85
+ if not boxes:
86
+ return [], []
87
+ idx = nms(boxes, scores)
88
+ boxes = [boxes[i] for i in idx]
89
+ scores = [scores[i] for i in idx]
90
+ if use_outliers:
91
+ keep = filter_outliers(boxes)
92
+ boxes = [boxes[i] for i in keep]
93
+ scores = [scores[i] for i in keep]
94
+ return boxes, scores
95
+
96
+
97
+ def select_inference_size(w: int, h: int) -> int:
98
+ if h > w * 1.3 or max(w, h) > 2400:
99
+ return 640
100
+ return 1024
101
+
102
+
103
+ def model_path_for_size(size: int) -> Path:
104
+ if size == 640:
105
+ p = ROOT / "static" / "models" / "countmodel-640.onnx"
106
+ if p.is_file():
107
+ return p
108
+ return ROOT / "static" / "models" / "countmodel.onnx"
109
+
110
+
111
+ def run_on_image(image_path: Path, out_path: Path):
112
+ img = cv2.imread(str(image_path))
113
+ if img is None:
114
+ raise FileNotFoundError(image_path)
115
+ h, w = img.shape[:2]
116
+ size = select_inference_size(w, h)
117
+ model_path = model_path_for_size(size)
118
+ session = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])
119
+ tensor, meta = letterbox(img, size)
120
+ t0 = time.perf_counter()
121
+ out = session.run(None, {"images": tensor})[0]
122
+ ms = (time.perf_counter() - t0) * 1000
123
+ boxes, scores = decode(out, meta, w, h)
124
+ vis = img.copy()
125
+ for i, (box, _sc) in enumerate(zip(boxes, scores), 1):
126
+ x1, y1, x2, y2 = map(int, box)
127
+ cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
128
+ r = max(10, min(x2 - x1, y2 - y1) // 2)
129
+ cv2.circle(vis, (cx, cy), r, (0, 0, 255), 2)
130
+ cv2.putText(vis, str(i), (cx - 8, cy + 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
131
+ cv2.putText(vis, f"Count: {len(boxes)}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)
132
+ cv2.imwrite(str(out_path), vis)
133
+ return len(boxes), ms, (w, h), size, model_path.name
134
+
135
+
136
+ def main():
137
+ images = [Path(p) for p in sys.argv[1:]] or [
138
+ Path(r"C:\Work\pipecountappv2026\sample1.jpg"),
139
+ Path(r"C:\Work\pipecountappv2026\sample2.jpg"),
140
+ ]
141
+ out_dir = ROOT / "test-output"
142
+ out_dir.mkdir(exist_ok=True)
143
+
144
+ print("Adaptive ONNX inference (640 for large portrait, 1024 otherwise)")
145
+ print("-" * 60)
146
+ for img_path in images:
147
+ if not img_path.is_file():
148
+ print(f"SKIP (not found): {img_path}")
149
+ continue
150
+ out_path = out_dir / f"{img_path.stem}-result.jpg"
151
+ count, ms, size, infer_size, model_name = run_on_image(img_path, out_path)
152
+ print(f"{img_path.name}")
153
+ print(f" Size: {size[0]}x{size[1]} px | model: {model_name} @ {infer_size}")
154
+ print(f" Pipes detected: {count}")
155
+ print(f" Inference: {ms:.0f} ms")
156
+ print(f" Annotated: {out_path}")
157
+ print()
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()