File size: 6,498 Bytes
ed9f15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# Source Code Structure

The application has been refactored into a modular structure for better maintainability and debugging.

## Directory Structure

```

src/

β”œβ”€β”€ config.js                    # Application configuration and constants

β”œβ”€β”€ state.js                     # Application state management

β”œβ”€β”€ main.js                      # Main entry point

β”‚

β”œβ”€β”€ models/                      # AI Model management

β”‚   β”œβ”€β”€ modelLoader.js          # Load and initialize ONNX models

β”‚   β”œβ”€β”€ inference.js            # Run model predictions

β”‚   └── yoloDetection.js        # YOLO-specific detection logic

β”‚

β”œβ”€β”€ processing/                  # Data processing

β”‚   β”œβ”€β”€ imagePreprocessing.js   # Image preprocessing for models

β”‚   β”œβ”€β”€ postprocessing.js       # Model output postprocessing

β”‚   └── yoloPostprocessing.js   # YOLO-specific postprocessing with NMS

β”‚

β”œβ”€β”€ ui/                          # UI components and handlers

β”‚   β”œβ”€β”€ eventHandlers.js        # Setup all event listeners

β”‚   β”œβ”€β”€ imageDisplay.js         # Image preview and display

β”‚   β”œβ”€β”€ loading.js              # Loading overlay controls

β”‚   β”œβ”€β”€ quickEval.js            # Quick evaluation handlers

β”‚   β”œβ”€β”€ results.js              # Results display and formatting

β”‚   β”œβ”€β”€ tabs.js                 # Tab switching logic

β”‚   β”œβ”€β”€ toast.js                # Toast notifications

β”‚   β”œβ”€β”€ workflow.js             # Main workflow logic

β”‚   └── zoom.js                 # Zoom controls

β”‚

└── utils/                       # Utility functions

    β”œβ”€β”€ imageUtils.js           # Image manipulation helpers

    └── mathUtils.js            # Math operations (softmax, etc.)

```

## Module Responsibilities

### Core Modules

**config.js**
- Model paths configuration
- Detection thresholds and parameters
- Label mappings
- ONNX Runtime configuration
- Zoom settings

**state.js**
- Centralized application state
- State getters and setters
- Current image, models, embryos tracking

**main.js**
- Application initialization
- Orchestrates model loading
- Sets up event listeners
- Entry point for the app

### Model Modules

**models/modelLoader.js**
- Initialize ONNX Runtime
- Load label mappings from config files
- Load all 4 ONNX models (classifier, quality, grader, YOLO)
- Provide model status

**models/inference.js**
- Run classification (embryo yes/no)
- Run quality check (poor/good)
- Run grading (Gardner scale)
- Orchestrate full embryo evaluation pipeline

**models/yoloDetection.js**
- Detect embryos using YOLO model
- Check YOLO availability

### Processing Modules

**processing/imagePreprocessing.js**
- Preprocess images for SigLIP models (224x224)
- Preprocess images for YOLO (640x640)
- Normalize with mean/std

**processing/postprocessing.js**
- Postprocess classification results
- Postprocess grading results with all predictions
- Apply softmax to logits

**processing/yoloPostprocessing.js**
- Parse YOLO output format [1, 5, 8400]
- Apply confidence threshold
- Non-Maximum Suppression (NMS)
- Calculate IoU (Intersection over Union)
- Crop detected embryo regions

### UI Modules

**ui/eventHandlers.js**
- Central event listener setup
- Handle image uploads
- Wire up all UI interactions

**ui/imageDisplay.js**
- Display images in main/quick previews
- Show cropped embryos
- Manage image visibility

**ui/loading.js**
- Show/hide loading overlay
- Update progress bar
- Display loading messages

**ui/quickEval.js**
- Quick evaluation workflow
- Clear quick evaluation results

**ui/results.js**
- Format and display results
- Interpret Gardner grades
- Show top-5 predictions
- Display classification status
- Generate image quality tips

**ui/tabs.js**
- Switch between main workflow and quick evaluation
- Manage tab state

**ui/toast.js**
- Show success/error/info toast notifications
- Auto-dismiss after 3 seconds

**ui/workflow.js**
- Main workflow orchestration
- Classify uploaded images
- Process single/multiple embryo modes
- Navigate between detected embryos
- Evaluate selected embryos

**ui/zoom.js**
- Adjust zoom level
- Reset zoom
- Apply zoom transform

### Utility Modules

**utils/imageUtils.js**
- Load images from URLs/data URIs
- Crop image regions with padding
- Read files as data URLs

**utils/mathUtils.js**
- Softmax function
- Mean calculation
- Value clamping

## Benefits of Modular Structure

1. **Easier Debugging**: Each module has a specific responsibility, making it easier to locate and fix bugs
2. **Better Testing**: Individual modules can be tested in isolation
3. **Code Reusability**: Functions can be easily imported and reused across different parts of the app
4. **Maintainability**: Changes to one module don't affect others if interfaces remain stable
5. **Readability**: Smaller files are easier to understand and navigate
6. **Collaboration**: Multiple developers can work on different modules simultaneously

## How to Add New Features

### Adding a New Model
1. Add model path to `config.js`
2. Load model in `models/modelLoader.js`
3. Create inference function in `models/inference.js`
4. Add preprocessing in `processing/imagePreprocessing.js` if needed
5. Add postprocessing in `processing/postprocessing.js`

### Adding a New UI Component
1. Create new file in `ui/` directory
2. Export relevant functions
3. Import and wire up in `ui/eventHandlers.js`
4. Update `main.js` if initialization is needed

### Modifying Detection Parameters
1. Update thresholds in `config.js`
2. No code changes needed elsewhere

## Import/Export Pattern

All modules use ES6 modules:
```javascript

// Export

export function myFunction() { ... }

export const myConstant = 42;



// Import

import { myFunction, myConstant } from './module.js';

```

## Debugging Tips

1. **Check browser console**: All errors are logged with descriptive messages
2. **Check Network tab**: Verify models are loading correctly
3. **Breakpoints**: Set breakpoints in specific modules to debug
4. **State inspection**: Check `appState` in console to see current state
5. **Module isolation**: Test individual functions by importing in console

## Backup

The original monolithic `app.js` has been backed up as `app.js.backup`.