sevensense-api 0.1.0

REST, GraphQL, and WebSocket API server for 7sense bioacoustics platform
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# sevensense-api

[![Crate](https://img.shields.io/badge/crates.io-sevensense--api-orange.svg)](https://crates.io/crates/sevensense-api)
[![Docs](https://img.shields.io/badge/docs-sevensense--api-blue.svg)](https://docs.rs/sevensense-api)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](../../LICENSE)

> HTTP API layer for the 7sense bioacoustic intelligence platform.

**sevensense-api** provides a comprehensive HTTP interface to all 7sense functionality. It offers GraphQL for flexible queries, REST endpoints with OpenAPI documentation, WebSocket streaming for real-time analysis, and Server-Sent Events for monitoring. Built on Axum for high performance and reliability.

## Features

- **GraphQL API**: Flexible queries with async-graphql
- **REST Endpoints**: OpenAPI/Swagger documented
- **WebSocket Streaming**: Real-time audio analysis
- **Authentication**: JWT-based auth with refresh tokens
- **Rate Limiting**: Configurable request throttling
- **Health Checks**: Kubernetes-ready probes

## Use Cases

| Use Case | Description | Endpoint |
|----------|-------------|----------|
| Species Identification | Identify birds from audio | `POST /api/identify` |
| Similarity Search | Find similar recordings | `POST /api/search` |
| Batch Processing | Process multiple files | `POST /api/batch` |
| Real-time Analysis | Stream audio for analysis | `WS /ws/stream` |
| Health Monitoring | Check system status | `GET /health` |

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
sevensense-api = "0.1"
```

## Quick Start

### Starting the Server

```bash
# Start with default configuration
cargo run -p sevensense-api --release

# With custom port
SEVENSENSE_PORT=8080 cargo run -p sevensense-api --release

# With configuration file
cargo run -p sevensense-api --release -- --config config.toml
```

### API Endpoints

Once running, access:
- **GraphQL Playground**: http://localhost:3000/graphql
- **Swagger UI**: http://localhost:3000/docs/swagger-ui
- **Health Check**: http://localhost:3000/health

---

<details>
<summary><b>Tutorial: GraphQL Queries</b></summary>

### Basic Species Query

```graphql
query {
  identifySpecies(audioUrl: "https://example.com/bird.wav") {
    predictions {
      speciesId
      commonName
      scientificName
      confidence
    }
    processingTime
  }
}
```

### Similarity Search

```graphql
query SearchSimilar($embedding: [Float!]!, $k: Int!) {
  searchSimilar(embedding: $embedding, k: $k, minSimilarity: 0.8) {
    id
    species {
      scientificName
      commonName
    }
    similarity
    recordingUrl
    timestamp
  }
}
```

### With Filters

```graphql
query FilteredSearch {
  searchSimilar(
    embedding: [0.1, 0.2, ...]
    k: 20
    filter: {
      species: ["Turdus merula", "Turdus philomelos"]
      location: { lat: 51.5, lon: -0.1, radiusKm: 50 }
      timeRange: { start: "2024-01-01", end: "2024-06-30" }
    }
  ) {
    id
    species { commonName }
    similarity
    location { lat, lon, siteName }
  }
}
```

### Mutations

```graphql
mutation AddRecording($input: RecordingInput!) {
  addRecording(input: $input) {
    id
    status
    embedding
  }
}

mutation DeleteRecording($id: ID!) {
  deleteRecording(id: $id) {
    success
    message
  }
}
```

### Subscriptions

```graphql
subscription OnNewDetection {
  newDetection(location: { lat: 51.5, lon: -0.1, radiusKm: 10 }) {
    id
    species { commonName }
    confidence
    timestamp
    audioUrl
  }
}
```

</details>

<details>
<summary><b>Tutorial: REST API</b></summary>

### Species Identification

```bash
# From file upload
curl -X POST http://localhost:3000/api/identify \
  -F "audio=@bird_call.wav"

# From URL
curl -X POST http://localhost:3000/api/identify \
  -H "Content-Type: application/json" \
  -d '{"audioUrl": "https://example.com/bird.wav"}'
```

Response:
```json
{
  "predictions": [
    {
      "speciesId": "turdus-merula",
      "scientificName": "Turdus merula",
      "commonName": "Eurasian Blackbird",
      "confidence": 0.94
    }
  ],
  "processingTimeMs": 127,
  "embedding": [0.123, -0.456, ...]
}
```

### Similarity Search

```bash
curl -X POST http://localhost:3000/api/search \
  -H "Content-Type: application/json" \
  -d '{
    "embedding": [0.123, -0.456, ...],
    "k": 10,
    "minSimilarity": 0.8
  }'
```

### Batch Processing

```bash
curl -X POST http://localhost:3000/api/batch \
  -H "Content-Type: application/json" \
  -d '{
    "audioUrls": [
      "https://example.com/bird1.wav",
      "https://example.com/bird2.wav",
      "https://example.com/bird3.wav"
    ],
    "options": {
      "includeEmbeddings": true,
      "topK": 3
    }
  }'
```

### Health Checks

```bash
# Liveness probe
curl http://localhost:3000/health/live

# Readiness probe
curl http://localhost:3000/health/ready

# Detailed status
curl http://localhost:3000/health/status
```

</details>

<details>
<summary><b>Tutorial: WebSocket Streaming</b></summary>

### Connecting to Stream

```javascript
const ws = new WebSocket('ws://localhost:3000/ws/stream');

ws.onopen = () => {
  console.log('Connected to stream');

  // Start streaming audio
  ws.send(JSON.stringify({
    type: 'start',
    config: {
      sampleRate: 32000,
      channels: 1,
      format: 'float32'
    }
  }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  if (message.type === 'detection') {
    console.log('Detection:', message.data);
  }
};

// Stream audio chunks
function sendAudioChunk(audioData) {
  ws.send(audioData);  // ArrayBuffer
}
```

### Rust Client

```rust
use sevensense_api::client::{StreamClient, StreamConfig};
use tokio_tungstenite::connect_async;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = StreamConfig {
        sample_rate: 32000,
        channels: 1,
        chunk_duration_ms: 500,
    };

    let client = StreamClient::connect("ws://localhost:3000/ws/stream", config).await?;

    // Send audio chunks
    for chunk in audio_chunks {
        client.send_audio(&chunk).await?;
    }

    // Receive detections
    while let Some(detection) = client.receive().await? {
        println!("Detected: {} ({:.1}%)",
            detection.species, detection.confidence * 100.0);
    }

    Ok(())
}
```

### Stream Protocol

| Message Type | Direction | Description |
|--------------|-----------|-------------|
| `start` | Client→Server | Start streaming with config |
| `audio` | Client→Server | Audio chunk (binary) |
| `stop` | Client→Server | Stop streaming |
| `detection` | Server→Client | Species detection event |
| `error` | Server→Client | Error message |
| `status` | Server→Client | Processing status |

</details>

<details>
<summary><b>Tutorial: Authentication</b></summary>

### JWT Authentication

```bash
# Login to get tokens
curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "user", "password": "pass"}'

# Response
{
  "accessToken": "eyJ...",
  "refreshToken": "eyJ...",
  "expiresIn": 3600
}

# Use access token
curl http://localhost:3000/api/search \
  -H "Authorization: Bearer eyJ..."

# Refresh token
curl -X POST http://localhost:3000/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{"refreshToken": "eyJ..."}'
```

### API Keys

```bash
# Create API key
curl -X POST http://localhost:3000/auth/api-keys \
  -H "Authorization: Bearer eyJ..." \
  -d '{"name": "My App", "scopes": ["read", "write"]}'

# Use API key
curl http://localhost:3000/api/search \
  -H "X-API-Key: sk_live_..."
```

### Scopes

| Scope | Description |
|-------|-------------|
| `read` | Read-only access to search and identify |
| `write` | Add/modify recordings |
| `admin` | Administrative operations |
| `stream` | Real-time streaming access |

</details>

<details>
<summary><b>Tutorial: Server Configuration</b></summary>

### Configuration File

```toml
# config.toml
[server]
host = "0.0.0.0"
port = 3000
workers = 4

[auth]
jwt_secret = "your-secret-key"
token_expiry_hours = 24
refresh_expiry_days = 30

[rate_limiting]
enabled = true
requests_per_minute = 100
burst_size = 20

[database]
url = "postgres://user:pass@localhost/sevensense"
max_connections = 20

[index]
path = "./data/hnsw.index"
preload = true

[logging]
level = "info"
format = "json"
```

### Environment Variables

```bash
# Server
export SEVENSENSE_HOST=0.0.0.0
export SEVENSENSE_PORT=3000

# Authentication
export SEVENSENSE_JWT_SECRET=your-secret
export SEVENSENSE_JWT_EXPIRY=3600

# Database
export DATABASE_URL=postgres://...

# Logging
export RUST_LOG=sevensense_api=info
```

### Programmatic Configuration

```rust
use sevensense_api::{Server, ServerConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig::builder()
        .host("0.0.0.0")
        .port(3000)
        .workers(4)
        .enable_graphql(true)
        .enable_swagger(true)
        .rate_limit(100, 20)
        .build()?;

    Server::new(config)
        .with_index(&index)
        .with_embedding_pipeline(&pipeline)
        .run()
        .await?;

    Ok(())
}
```

</details>

---

## API Reference

### GraphQL Schema

| Type | Description |
|------|-------------|
| `Query.identifySpecies` | Identify species from audio |
| `Query.searchSimilar` | Find similar recordings |
| `Query.getRecording` | Get recording by ID |
| `Mutation.addRecording` | Add new recording |
| `Subscription.newDetection` | Real-time detection events |

### REST Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api/identify` | Identify species |
| `POST` | `/api/search` | Similarity search |
| `POST` | `/api/batch` | Batch processing |
| `GET` | `/api/recordings/:id` | Get recording |
| `WS` | `/ws/stream` | Real-time streaming |

### Health Endpoints

| Path | Description |
|------|-------------|
| `/health/live` | Liveness probe |
| `/health/ready` | Readiness probe |
| `/health/status` | Detailed status |

## Performance

| Metric | Target | Actual |
|--------|--------|--------|
| Identify Latency | <200ms | ~150ms |
| Search Latency | <50ms | ~35ms |
| Concurrent Connections | 1000 ||
| Requests/Second | 500 | ~600 |

## Links

- **Homepage**: [ruv.io]https://ruv.io
- **Repository**: [github.com/ruvnet/ruvector]https://github.com/ruvnet/ruvector
- **Crates.io**: [crates.io/crates/sevensense-api]https://crates.io/crates/sevensense-api
- **Documentation**: [docs.rs/sevensense-api]https://docs.rs/sevensense-api

## License

MIT License - see [LICENSE](../../LICENSE) for details.

---

*Part of the [7sense Bioacoustic Intelligence Platform](https://ruv.io) by rUv*