# Pulse Monitor v2 - Project Context

## Overview
Pulse oximeter digit recognition system that reads SpO2 and HR values from a 7-segment LED display using camera capture and scan-line analysis.

## Architecture
- **main.go**: Core digit recognition using scan-line analysis at y=2/5 and y=4/5 heights
- **patterns.go**: Web-based training interface and pattern storage
- **hass.go**: Home Assistant integration for reporting values

## Digit Recognition Approach

### Fingerprint-Based Classification
Each digit is classified by its **fingerprint**: white pixel percentage at two scan lines, rounded to 5%.

Format: `{p2}_{p4}` where:
- `p2` = white pixels % at y = 2/5 of digit height
- `p4` = white pixels % at y = 4/5 of digit height

Example: A "9" might have fingerprint "75_90" meaning 75% white at 2/5 height, 90% white at 4/5 height.

### Learning System
1. **Pattern Store** (patterns.csv): Maps fingerprints to digit values
2. **Unlabeled Queue**: New fingerprints are saved with digit images
3. **Web GUI** (http://localhost:8090): Shows digit images for manual labeling
4. **Fallback Matcher**: Uses distance-based matching against initial guesses

### Flow
1. Capture frame → extract digit regions
2. For each digit:
   - Calculate fingerprint (p2_p4)
   - Check patterns.csv for learned value
   - If unknown: save image, queue for labeling, use fallback guess
3. Web GUI shows queued patterns with images
4. User labels patterns → saved to patterns.csv
5. Future recognition uses learned values

## Leading "1" Detection (3-digit numbers)
HR values 100-199 start with "1". Three strategies detect leading "1":
1. **Strategy 1**: Narrow both-white region followed by both-dark gap
2. **Strategy 2**: Narrow first run at y=58 when "1" merges with next digit at y=29
3. **Strategy 3**: Wide total content (>100px) with first y=58 run 40-65% of width (merged "1"+"0")

## Key Files
- `patterns.csv`: Learned fingerprint → digit mappings
- `digit_left_N_FP.png` / `digit_right_N_FP.png`: Saved digit images for labeling
- `debug_cuts_left.png` / `debug_cuts_right.png`: Debug visualization of digit boundaries

## Web Training Interface
- URL: http://localhost:8090
- Shows unlabeled digit images with fingerprints
- Enter digit value (0-9) and press Enter to save
- Enter "x" or "-1" to mark as ignore/invalid

## Current Status
- SpO2 recognition: Working (92 reads correctly)
- HR recognition: Needs fingerprint calibration
- Next step: Run monitor, open GUI, label patterns to build patterns.csv

## Run Commands
```bash
go build -o pulse-monitor .
./pulse-monitor
# Open http://localhost:8090 for training GUI
```
