-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetections.ts
More file actions
182 lines (164 loc) · 5.86 KB
/
detections.ts
File metadata and controls
182 lines (164 loc) · 5.86 KB
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
import { getDb } from './database';
import type { Detection, DetectionFilter, SpeciesSummary, CatalogStats } from '$shared/types';
import type { BirdaDetection } from '../birda/types';
function escapeLike(str: string): string {
return str.replace(/[%_\\]/g, '\\$&');
}
export function insertDetections(
runId: number,
locationId: number | null,
sourceFile: string,
detections: BirdaDetection[],
): void {
const db = getDb();
const stmt = db.prepare(`
INSERT INTO detections (run_id, location_id, source_file, start_time, end_time, scientific_name, confidence)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
const insertMany = db.transaction((dets: BirdaDetection[]) => {
for (const d of dets) {
stmt.run(runId, locationId, sourceFile, d.start_time, d.end_time, d.scientific_name, d.confidence);
}
});
insertMany(detections);
}
export function getDetections(filter: DetectionFilter): { detections: Detection[]; total: number } {
const db = getDb();
const conditions: string[] = [];
const params: unknown[] = [];
if (filter.scientific_names && filter.scientific_names.length > 0) {
// Pre-resolved scientific names (e.g. from label service common name search)
const placeholders = filter.scientific_names.map(() => '?').join(', ');
if (filter.species) {
// Also match scientific_name by LIKE in case the query is a partial scientific name
conditions.push(`(scientific_name IN (${placeholders}) OR scientific_name LIKE ? ESCAPE '\\')`);
params.push(...filter.scientific_names, `%${escapeLike(filter.species)}%`);
} else {
conditions.push(`scientific_name IN (${placeholders})`);
params.push(...filter.scientific_names);
}
} else if (filter.species) {
conditions.push("scientific_name LIKE ? ESCAPE '\\'");
const escaped = escapeLike(filter.species);
params.push(`%${escaped}%`);
}
if (filter.location_id) {
conditions.push('location_id = ?');
params.push(filter.location_id);
}
if (filter.min_confidence) {
conditions.push('confidence >= ?');
params.push(filter.min_confidence);
}
if (filter.run_id) {
conditions.push('run_id = ?');
params.push(filter.run_id);
}
if (filter.species_list_id) {
conditions.push('scientific_name IN (SELECT scientific_name FROM species_list_entries WHERE list_id = ?)');
params.push(filter.species_list_id);
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const limit = filter.limit ?? 100;
const offset = filter.offset ?? 0;
// Whitelist allowed sort columns to prevent SQL injection
const allowedSortColumns = new Set(['scientific_name', 'confidence', 'start_time', 'source_file', 'detected_at']);
const sortCol = filter.sort_column && allowedSortColumns.has(filter.sort_column) ? filter.sort_column : 'detected_at';
const sortDir = filter.sort_dir === 'asc' ? 'ASC' : 'DESC';
const total = (db.prepare(`SELECT COUNT(*) as count FROM detections ${where}`).get(...params) as { count: number })
.count;
const detections = db
.prepare(`SELECT * FROM detections ${where} ORDER BY ${sortCol} ${sortDir} LIMIT ? OFFSET ?`)
.all(...params, limit, offset) as Detection[];
return { detections, total };
}
export function searchSpecies(query: string, scientificNames?: string[]): SpeciesSummary[] {
const db = getDb();
const escaped = escapeLike(query);
if (scientificNames && scientificNames.length > 0) {
// Search by scientific name LIKE or by pre-resolved names from label service
const placeholders = scientificNames.map(() => '?').join(', ');
return db
.prepare(
`
SELECT * FROM species_summary
WHERE scientific_name LIKE ? ESCAPE '\\' OR scientific_name IN (${placeholders})
ORDER BY detection_count DESC
LIMIT 20
`,
)
.all(`%${escaped}%`, ...scientificNames) as SpeciesSummary[];
}
return db
.prepare(
`
SELECT * FROM species_summary
WHERE scientific_name LIKE ? ESCAPE '\\'
ORDER BY detection_count DESC
LIMIT 20
`,
)
.all(`%${escaped}%`) as SpeciesSummary[];
}
export function getSpeciesSummary(): SpeciesSummary[] {
const db = getDb();
return db.prepare('SELECT * FROM species_summary ORDER BY detection_count DESC').all() as SpeciesSummary[];
}
export function getSpeciesLocations(
scientificName: string,
): { location_id: number; latitude: number; longitude: number; name: string | null; detection_count: number }[] {
const db = getDb();
return db
.prepare(
`
SELECT d.location_id, l.latitude, l.longitude, l.name, COUNT(*) as detection_count
FROM detections d
JOIN locations l ON d.location_id = l.id
WHERE d.scientific_name = ?
GROUP BY d.location_id
`,
)
.all(scientificName) as {
location_id: number;
latitude: number;
longitude: number;
name: string | null;
detection_count: number;
}[];
}
export function getLocationSpecies(locationId: number): SpeciesSummary[] {
const db = getDb();
return db
.prepare(
`
SELECT scientific_name,
1 as location_count,
COUNT(*) as detection_count,
MAX(detected_at) as last_detected,
AVG(confidence) as avg_confidence
FROM detections
WHERE location_id = ?
GROUP BY scientific_name
ORDER BY detection_count DESC
`,
)
.all(locationId) as SpeciesSummary[];
}
export function getCatalogStats(): CatalogStats {
const db = getDb();
const result = db
.prepare(
`
SELECT
(SELECT COUNT(*) FROM detections) as total_detections,
(SELECT COUNT(DISTINCT scientific_name) FROM detections) as total_species,
(SELECT COUNT(*) FROM locations) as total_locations
`,
)
.get() as CatalogStats;
return result;
}
export function updateDetectionClipPath(id: number, clipPath: string): void {
const db = getDb();
db.prepare('UPDATE detections SET clip_path = ? WHERE id = ?').run(clipPath, id);
}