# Examples & Sample Projects

Real-world code examples and complete sample projects to help you build with Presage.

## Quick Examples

### Basic Prediction (Python)

```python
from presage import Presage

client = Presage()

result = client.predict(
    model="presage-vitals-v1",
    input={
        "heart_rate": 88,
        "blood_pressure_systolic": 145,
        "blood_pressure_diastolic": 92,
        "respiratory_rate": 22,
        "temperature": 99.1,
        "oxygen_saturation": 94
    }
)

print(f"Risk Level: {result.prediction['risk_level']}")
print(f"Risk Score: {result.prediction['risk_score']:.2f}")
print(f"Confidence: {result.prediction['confidence']:.2f}")
```

### Batch Processing (Python)

```python
from presage import Presage
import pandas as pd

client = Presage()

# Load patient data from CSV
df = pd.read_csv("patient_vitals.csv")

# Convert to list of input dicts
inputs = df.to_dict('records')

# Batch predict (up to 100 at a time)
results = client.predict_batch(
    model="presage-vitals-v1",
    inputs=inputs
)

# Add predictions back to dataframe
df['risk_score'] = [r['risk_score'] for r in results.predictions]
df['risk_level'] = [r['risk_level'] for r in results.predictions]

# Filter high-risk patients
high_risk = df[df['risk_level'].isin(['high', 'critical'])]
print(f"Found {len(high_risk)} high-risk patients")
```

### Async Predictions (Node.js)

```javascript
import { Presage } from '@presage/sdk';

const client = new Presage();

async function assessPatients(patients) {
  const results = await Promise.all(
    patients.map(patient =>
      client.predict({
        model: 'presage-vitals-v1',
        input: patient.vitals
      })
    )
  );

  return results.map((result, i) => ({
    patientId: patients[i].id,
    ...result.prediction
  }));
}

// Usage
const patients = [
  { id: 'P001', vitals: { heart_rate: 72, ... } },
  { id: 'P002', vitals: { heart_rate: 95, ... } },
];

const assessments = await assessPatients(patients);
console.log(assessments);
```

### Error Handling (Python)

```python
from presage import Presage
from presage.exceptions import (
    PresageAPIError,
    RateLimitError,
    InvalidInputError,
    AuthenticationError
)
import time

client = Presage()

def predict_with_retry(input_data, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.predict(
                model="presage-vitals-v1",
                input=input_data
            )
        except RateLimitError as e:
            if attempt < max_retries - 1:
                wait_time = e.retry_after or (2 ** attempt)
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise
        except InvalidInputError as e:
            print(f"Invalid input: {e.message}")
            print(f"Problem field: {e.param}")
            raise
        except AuthenticationError:
            print("Check your API key")
            raise
        except PresageAPIError as e:
            print(f"API error: {e.message}")
            raise
```

### Webhook Integration (Node.js)

```javascript
import express from 'express';
import { Presage } from '@presage/sdk';

const app = express();
const client = new Presage();

app.use(express.json());

// Receive vitals from monitoring device
app.post('/webhook/vitals', async (req, res) => {
  const { patientId, vitals, timestamp } = req.body;

  try {
    const result = await client.predict({
      model: 'presage-vitals-v1',
      input: vitals
    });

    // Alert if high risk
    if (['high', 'critical'].includes(result.prediction.risk_level)) {
      await sendAlert({
        patientId,
        riskLevel: result.prediction.risk_level,
        riskScore: result.prediction.risk_score,
        timestamp
      });
    }

    // Store result
    await saveAssessment(patientId, result);

    res.json({ status: 'processed', riskLevel: result.prediction.risk_level });
  } catch (error) {
    console.error('Assessment failed:', error);
    res.status(500).json({ error: 'Assessment failed' });
  }
});

app.listen(3000);
```

---

## Sample Projects

### 1. Patient Monitoring Dashboard

A complete React dashboard for monitoring patient risk scores in real-time.

**Features**:
- Real-time vitals display
- Risk score visualization
- Alert notifications
- Historical trends

**Repository**: [github.com/Presage-Security/SmartSpectra](https://github.com/Presage-Security/SmartSpectra)

```bash
git clone https://github.com/Presage-Security/SmartSpectra
cd example-dashboard
npm install
cp .env.example .env  # Add your PRESAGE_API_KEY
npm run dev
```

---

### 2. EHR Integration (FHIR)

Python library for integrating Presage with FHIR-based EHR systems.

**Features**:
- FHIR R4 patient data extraction
- Automatic vital signs mapping
- Observation resource creation for results

**Repository**: [github.com/Presage-Security/SmartSpectra](https://github.com/Presage-Security/SmartSpectra)

```python
from presage_fhir import FHIRClient, PresageIntegration

fhir = FHIRClient(base_url="https://your-ehr.com/fhir")
presage = PresageIntegration()

# Get patient and assess
patient = fhir.get_patient("12345")
vitals = fhir.get_latest_vitals(patient.id)
assessment = presage.assess(vitals)

# Write result back as Observation
fhir.create_observation(
    patient=patient,
    code="presage-risk-score",
    value=assessment.risk_score
)
```

---

### 3. Mobile SDK Demo (React Native)

Cross-platform mobile app demonstrating Presage integration for remote patient monitoring.

**Repository**: [github.com/Presage-Security/SmartSpectra](https://github.com/Presage-Security/SmartSpectra)

---

### 4. CLI Tool

Command-line tool for quick predictions and batch processing.

```bash
pip install presage-cli

# Single prediction
presage predict --model presage-vitals-v1 \
  --hr 72 --sbp 120 --dbp 80 --rr 16 --temp 98.6 --spo2 98

# Batch from CSV
presage batch --model presage-vitals-v1 \
  --input patients.csv --output results.csv
```

**Repository**: [github.com/Presage-Security/SmartSpectra](https://github.com/Presage-Security/SmartSpectra)

---

## Community Projects

Projects built by the Presage developer community:

| Project | Description | Author |
|---------|-------------|--------|
| presage-grafana | Grafana dashboard for Presage metrics | @community-dev |
| presage-slack | Slack bot for risk alerts | @community-dev |
| presage-airflow | Airflow DAGs for batch processing | @community-dev |

*Want your project featured? Email community@presage.tech*

---

## Request a Demo

Need help with a specific integration? Our solutions team can help.

- Schedule a call: [calendly.com/presage-demo](https://calendly.com/presage-demo)
- Email: solutions@presage.tech
