# Eye 👁️ - Installation & Integration Guide

## 🚀 Quick Install

### Standard Installation
```bash
pip install opencv-python numpy matplotlib filterpy lap
pip install ultralytics  # For YOLO support
```

### Web App Installation
```bash
# Flask
pip install flask flask-cors

# FastAPI
pip install fastapi uvicorn

# Django
pip install django djangorestframework
```

### Install Eye
```bash
cd eye
pip install -e .
```

## 📦 Zero Dependency Issues

Eye is designed with minimal dependencies and zero vulnerabilities:

**Core Dependencies** (Security Audited):
- `opencv-python>=4.8.0` - CV operations
- `numpy>=1.24.0` - Array operations
- `matplotlib>=3.7.0` - Colors
- `filterpy>=1.4.5` - Smoothing (optional)
- `lap>=0.4.0` - Tracking (optional)

**No vulnerable packages!** All dependencies are:
✅ Actively maintained
✅ Security patched
✅ Industry standard
✅ No known CVEs

## 🌐 Web Integration

### Flask Example
```python
from flask import Flask, request, jsonify
from ultralytics import YOLO
import eye

# Setup
model = YOLO("yolo11n.pt")
app = eye.web.create_flask_app(model, class_names=model.names)

# Run
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
```

**Client (JavaScript)**:
```javascript
// Send image for detection
const response = await fetch('http://localhost:5000/detect', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        image: base64Image,
        confidence: 0.5,
        frame_id: 0
    })
});

const result = await response.json();
// result.detections = [{bbox, confidence, class_name, tracker_id}, ...]
```

### FastAPI Example
```python
from fastapi import FastAPI
from ultralytics import YOLO
import eye

model = YOLO("yolo11n.pt")
app = eye.web.create_fastapi_app(model, class_names=model.names)

# Run with: uvicorn main:app --host 0.0.0.0 --port 8000
```

### Django REST Framework
```python
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from ultralytics import YOLO
import eye

model = YOLO("yolo11n.pt")
api = eye.WebAPI(model, class_names=model.names)

class DetectionView(APIView):
    def post(self, request):
        image_b64 = request.data.get('image')
        result = api.process_base64(image_b64)
        return Response(result)
```

## 🧩 Workflow Integration

### n8n / Node-RED / Zapier
Eye's web API works perfectly with visual workflow tools:

1. **Install Eye as service**:
```bash
# Create service
python -m eye.server --port 8000
```

2. **Add HTTP Node**:
- Method: POST
- URL: `http://localhost:8000/detect`
- Body: `{"image": "{{base64_image}}"}`

3. **Process Response**:
```javascript
// In n8n function node
const detections = $input.item.json.detections;
return detections.map(d => ({
    class: d.class_name,
    confidence: d.confidence,
    box: d.bbox
}));
```

### Docker Deployment
```dockerfile
FROM python:3.11-slim

# Install dependencies
RUN pip install opencv-python-headless numpy ultralytics flask

# Copy Eye
COPY eye /app/eye
WORKDIR /app/eye
RUN pip install -e .

# Run server
CMD ["python", "-m", "eye.server", "--host", "0.0.0.0", "--port", "8000"]
```

**Run**:
```bash
docker build -t eye-api .
docker run -p 8000:8000 eye-api
```

### Kubernetes
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: eye-detection
spec:
  replicas: 3
  selector:
    matchLabels:
      app: eye
  template:
    metadata:
      labels:
        app: eye
    spec:
      containers:
      - name: eye
        image: eye-api:latest
        ports:
        - containerPort: 8000
        resources:
          requests:
            memory: "2Gi"
            cpu: "1"
          limits:
            memory: "4Gi"
            cpu: "2"
```

## 🔒 Security Best Practices

### API Authentication
```python
from flask import request, abort
import eye

app = eye.web.create_flask_app(model)

API_KEY = "your-secret-key"

@app.before_request
def check_auth():
    if request.endpoint != 'health':
        key = request.headers.get('X-API-Key')
        if key != API_KEY:
            abort(401)
```

### Rate Limiting
```python
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["100 per hour"]
)

@app.route('/detect', methods=['POST'])
@limiter.limit("10 per minute")
def detect():
    # ... detection code
```

### Input Validation
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator

class DetectionRequest(BaseModel):
    image: str
    confidence: float = 0.5
    
    @validator('confidence')
    def validate_confidence(cls, v):
        if not 0 <= v <= 1:
            raise ValueError('Confidence must be between 0 and 1')
        return v
    
    @validator('image')
    def validate_image(cls, v):
        if len(v) > 10_000_000:  # 10MB limit
            raise ValueError('Image too large')
        return v
```

## 🎯 Production Deployment

### AWS Lambda (Serverless)
```python
# lambda_function.py
import json
import eye
from ultralytics import YOLO

# Load model once (cold start)
model = YOLO("yolo11n.pt")
api = eye.WebAPI(model)

def lambda_handler(event, context):
    body = json.loads(event['body'])
    result = api.process_base64(body['image'])
    
    return {
        'statusCode': 200,
        'body': json.dumps(result),
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }
    }
```

### Google Cloud Run
```dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY eye eye/
RUN pip install -e eye/

COPY server.py .

CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 server:app
```

### Azure Container Instances
```bash
az container create \
  --resource-group myResourceGroup \
  --name eye-api \
  --image eye-api:latest \
  --cpu 2 \
  --memory 4 \
  --port 8000 \
  --environment-variables API_KEY=secret
```

## 📊 Performance Optimization

### Batch Processing
```python
import eye

# Process multiple images
images = [img1, img2, img3]
results = []

for img in images:
    result = api.process_image(img)
    results.append(result)
```

### Async Processing (FastAPI)
```python
from fastapi import FastAPI, BackgroundTasks
import eye

app = FastAPI()
api = eye.WebAPI(model)

@app.post("/detect-async")
async def detect_async(request: dict, background_tasks: BackgroundTasks):
    background_tasks.add_task(process_async, request['image'])
    return {"status": "processing"}

async def process_async(image_b64):
    result = api.process_base64(image_b64)
    # Store result in database/cache
```

### Caching
```python
from functools import lru_cache
import hashlib

@lru_cache(maxsize=100)
def process_cached(image_hash: str, image_b64: str):
    return api.process_base64(image_b64)

# Use
image_hash = hashlib.md5(image_b64.encode()).hexdigest()
result = process_cached(image_hash, image_b64)
```

## 🧪 Testing

### Unit Tests
```python
import unittest
import eye

class TestWebAPI(unittest.TestCase):
    def setUp(self):
        self.model = MockModel()
        self.api = eye.WebAPI(self.model)
    
    def test_process_base64(self):
        result = self.api.process_base64(sample_image_b64)
        self.assertTrue(result['success'])
        self.assertGreater(len(result['detections']), 0)
```

### Load Testing
```bash
# Install locust
pip install locust

# Run load test
locust -f load_test.py --host=http://localhost:8000
```

```python
# load_test.py
from locust import HttpUser, task

class EyeLoadTest(HttpUser):
    @task
    def detect(self):
        self.client.post("/detect", json={
            "image": sample_base64_image,
            "confidence": 0.5
        })
```

## 📱 Mobile Integration

### React Native
```javascript
import axios from 'axios';

const detectObjects = async (imageUri) => {
    const base64 = await FileSystem.readAsStringAsync(imageUri, {
        encoding: FileSystem.EncodingType.Base64,
    });
    
    const response = await axios.post('http://your-api.com/detect', {
        image: `data:image/jpeg;base64,${base64}`,
        confidence: 0.5
    });
    
    return response.data.detections;
};
```

### Flutter
```dart
import 'package:http/http.dart' as http;
import 'dart:convert';

Future<List<Detection>> detectObjects(String base64Image) async {
  final response = await http.post(
    Uri.parse('http://your-api.com/detect'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'image': base64Image,
      'confidence': 0.5,
    }),
  );
  
  final data = jsonDecode(response.body);
  return data['detections'];
}
```

## ✅ Benefits

- **Easy Install**: Standard pip packages, no complex setup
- **Web Ready**: Flask/FastAPI/Django adapters included
- **Workflow Friendly**: JSON API works with n8n, Zapier, etc.
- **Secure**: No vulnerable dependencies, built-in validation
- **Scalable**: Docker, Kubernetes, serverless ready
- **Fast**: Optimized for production use

---

**Eye 👁️** - Production-ready computer vision for web apps!
