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 
 
 
 
 
 
 
 
 
 
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# πŸ›‘οΈ Police Bot AI Integration Guide

This guide explains how to integrate the AI wellness assistant with your website and enhance it with additional local LLM capabilities.

## πŸ—οΈ System Architecture

```
Website Frontend (React/HTML/CSS)
    ↓ HTTP/WebSocket
Flask Web API (web_api.py)
    ↓
Police Bot Runtime (police_runtime.py)
    ↓
β”œβ”€β”€ LLaMA3 via Ollama (Primary Reasoning)
β”œβ”€β”€ F5-TTS (Voice Synthesis)
└── [Third Local LLM] (Enhanced Capabilities)
```

## πŸš€ Quick Start

### 1. Setup the AI Runtime

```bash
# Run the setup script
python setup.py

# Start Ollama with the police-bot model
ollama run police-bot

# Start the web API
python web_api.py
```

### 2. Test the System

```bash
# Test the command-line interface
python police_runtime.py

# Test the web API
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "I am feeling stressed today"}'
```

## 🌐 Website Integration

### Option 1: Simple HTML Integration

Add this to your website:

```html
<!DOCTYPE html>
<html>
<head>
    <title>Police Wellness Assistant</title>
    <style>
        .police-bot-chat {
            max-width: 600px;
            margin: 20px auto;
            border: 1px solid #ccc;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .chat-header {
            background: #1e40af;
            color: white;
            padding: 15px;
            text-align: center;
        }
        
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
            background: #f8fafc;
        }
        
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 8px;
        }
        
        .user-message {
            background: #dbeafe;
            margin-left: 20%;
        }
        
        .bot-message {
            background: white;
            margin-right: 20%;
        }
        
        .chat-input {
            display: flex;
            padding: 15px;
            background: white;
        }
        
        .chat-input input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-right: 10px;
        }
        
        .chat-input button {
            padding: 10px 20px;
            background: #1e40af;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .wellness-tips {
            padding: 15px;
            background: #f0f9ff;
            border-top: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="police-bot-container"></div>
    
    <script src="static/js/police-bot-client.js"></script>
    <script>
        // Initialize the Police Bot UI
        const policeBot = new PoliceBotUI('police-bot-container');
    </script>
</body>
</html>
```

### Option 2: React Integration

```jsx
import React, { useState, useEffect } from 'react';
import { PoliceBotClient } from './police-bot-client.js';

function PoliceBotChat() {
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');
    const [isProcessing, setIsProcessing] = useState(false);
    const [wellnessTips, setWellnessTips] = useState([]);
    
    const client = new PoliceBotClient('http://localhost:5000');
    
    const sendMessage = async () => {
        if (!input.trim() || isProcessing) return;
        
        const userMessage = { text: input, sender: 'user', timestamp: Date.now() };
        setMessages(prev => [...prev, userMessage]);
        setInput('');
        setIsProcessing(true);
        
        try {
            await client.sendMessage(
                input,
                (response) => {
                    const botMessage = { 
                        text: response.text, 
                        sender: 'bot', 
                        timestamp: Date.now() 
                    };
                    setMessages(prev => [...prev, botMessage]);
                    setWellnessTips(response.wellness_tips || []);
                },
                (error) => {
                    const errorMessage = { 
                        text: `Error: ${error}`, 
                        sender: 'bot', 
                        timestamp: Date.now() 
                    };
                    setMessages(prev => [...prev, errorMessage]);
                }
            );
        } finally {
            setIsProcessing(false);
        }
    };
    
    return (
        <div className="police-bot-chat">
            <div className="chat-header">
                <h3>πŸ›‘οΈ Police Wellness Assistant</h3>
            </div>
            
            <div className="chat-messages">
                {messages.map((msg, index) => (
                    <div key={index} className={`message ${msg.sender}-message`}>
                        {msg.text}
                    </div>
                ))}
            </div>
            
            <div className="chat-input">
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                    placeholder="Type your message..."
                    disabled={isProcessing}
                />
                <button onClick={sendMessage} disabled={isProcessing}>
                    {isProcessing ? 'Processing...' : 'Send'}
                </button>
            </div>
            
            {wellnessTips.length > 0 && (
                <div className="wellness-tips">
                    <h4>Wellness Tips</h4>
                    <ul>
                        {wellnessTips.map((tip, index) => (
                            <li key={index}>{tip}</li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    );
}

export default PoliceBotChat;
```

## πŸ€– Adding a Third Local LLM

You can enhance the system with additional local LLMs for specialized tasks:

### Option 1: Emotion Analysis LLM

```python
# Add to police_runtime.py
def get_emotion_llm_response(self, text: str) -> str:
    """Get emotion analysis from a dedicated LLM"""
    try:
        # You can use a smaller, specialized model for emotion analysis
        data = {
            "model": "emotion-analyzer",  # Different Ollama model
            "prompt": f"Analyze the emotional state of this text: '{text}'. Respond with only: stressed, positive, negative, or neutral.",
            "stream": False,
            "options": {
                "temperature": 0.1,  # Lower temperature for consistent analysis
                "max_tokens": 10
            }
        }
        
        response = requests.post(self.ollama_url, json=data, timeout=10)
        response.raise_for_status()
        
        result = response.json()
        emotion = result.get("response", "").strip().lower()
        
        # Validate emotion
        valid_emotions = ["stressed", "positive", "negative", "neutral"]
        return emotion if emotion in valid_emotions else "neutral"
        
    except Exception as e:
        logger.error(f"Error in emotion analysis: {e}")
        return "neutral"
```

### Option 2: Wellness Recommendation LLM

```python
def get_wellness_llm_response(self, emotional_state: str, context: str = "") -> list:
    """Get personalized wellness recommendations from a specialized LLM"""
    try:
        prompt = f"""
        As a wellness expert for police officers, provide 3-4 specific, actionable wellness tips for someone who is feeling {emotional_state}.
        
        Context: {context}
        
        Focus on:
        - Quick, practical interventions (2-5 minutes)
        - Stress management techniques
        - Physical wellness (hydration, movement)
        - Mental wellness (mindfulness, perspective)
        
        Respond with only the tips, one per line, no numbering.
        """
        
        data = {
            "model": "wellness-expert",  # Specialized wellness model
            "prompt": prompt,
            "stream": False,
            "options": {
                "temperature": 0.7,
                "max_tokens": 200
            }
        }
        
        response = requests.post(self.ollama_url, json=data, timeout=15)
        response.raise_for_status()
        
        result = response.json()
        tips_text = result.get("response", "").strip()
        
        # Parse tips into list
        tips = [tip.strip() for tip in tips_text.split('\n') if tip.strip()]
        return tips[:4]  # Limit to 4 tips
        
    except Exception as e:
        logger.error(f"Error in wellness recommendations: {e}")
        return self.generate_wellness_tips(emotional_state)  # Fallback
```

### Option 3: Multi-Model Setup

Create a model manager to handle multiple LLMs:

```python
class ModelManager:
    def __init__(self):
        self.models = {
            "primary": "police-bot",      # Main conversation
            "emotion": "emotion-analyzer", # Emotion analysis
            "wellness": "wellness-expert", # Wellness recommendations
            "kannada": "kannada-assistant" # Kannada language support
        }
    
    def get_response(self, model_type: str, prompt: str, **kwargs) -> str:
        """Get response from specified model"""
        model_name = self.models.get(model_type, "police-bot")
        
        data = {
            "model": model_name,
            "prompt": prompt,
            "stream": False,
            **kwargs
        }
        
        response = requests.post("http://localhost:11434/api/generate", json=data)
        return response.json().get("response", "").strip()
```

## πŸ”§ Configuration

### Environment Variables

Create a `.env` file:

```env
# Ollama Configuration
OLLAMA_URL=http://localhost:11434
OLLAMA_MODEL=police-bot

# F5-TTS Configuration
F5TTS_CKPT=C:\Users\Samarth Kadam\Voice-train\F5-TTS\ckpts\my_speak\model_last.pt
F5TTS_SCRIPT=C:\Users\Samarth Kadam\Voice-train\F5-TTS\src\f5_tts\infer\infer_cli.py

# Web API Configuration
WEB_PORT=5000
WEB_HOST=0.0.0.0

# Security
API_KEY=your-secret-api-key
```

### CORS Configuration

For production deployment, configure CORS properly:

```python
# In web_api.py
from flask_cors import CORS

app = Flask(__name__)
CORS(app, origins=[
    "http://localhost:3000",  # React dev server
    "http://your-website.com", # Production website
    "https://your-website.com"
])
```

## πŸš€ Production Deployment

### Using Gunicorn

```bash
# Install gunicorn
pip install gunicorn

# Start production server
gunicorn -w 4 -b 0.0.0.0:5000 web_api:app
```

### Using Docker

```dockerfile
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 5000

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "web_api:app"]
```

### Systemd Service (Linux)

```ini
# /etc/systemd/system/police-bot.service
[Unit]
Description=Police Bot AI Runtime
After=network.target

[Service]
Type=simple
User=police-bot
WorkingDirectory=/opt/police-bot-runtime
Environment=PATH=/opt/police-bot-runtime/venv/bin
ExecStart=/opt/police-bot-runtime/venv/bin/python web_api.py
Restart=always

[Install]
WantedBy=multi-user.target
```

## πŸ”’ Security Considerations

1. **API Authentication**: Add API key validation
2. **Rate Limiting**: Implement request rate limiting
3. **Input Validation**: Sanitize all user inputs
4. **HTTPS**: Use SSL/TLS in production
5. **Firewall**: Restrict access to necessary ports only

## πŸ“Š Monitoring and Logging

```python
# Add to web_api.py
import logging
from logging.handlers import RotatingFileHandler

# Configure logging
if not app.debug:
    file_handler = RotatingFileHandler('logs/police_bot.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Police Bot startup')
```

## πŸ§ͺ Testing

### API Testing

```bash
# Test chat endpoint
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "I am feeling stressed today"}'

# Test health endpoint
curl http://localhost:5000/health

# Test status endpoint
curl http://localhost:5000/api/status
```

### Load Testing

```python
import requests
import time
import threading

def test_load():
    for i in range(10):
        response = requests.post('http://localhost:5000/api/chat', 
                               json={'message': f'Test message {i}'})
        print(f'Request {i}: {response.status_code}')

# Run multiple threads
threads = [threading.Thread(target=test_load) for _ in range(5)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
```

## 🎯 Next Steps

1. **Voice Avatar**: Add a visual avatar that speaks
2. **Multi-language**: Implement Kannada language support
3. **Session Management**: Add user session tracking
4. **Analytics**: Track usage patterns and wellness trends
5. **Mobile App**: Create a mobile companion app
6. **Integration**: Connect with existing police systems

## πŸ“ž Support

For technical support or questions:
- Check the logs in the `logs/` directory
- Verify all services are running: `python setup.py`
- Test individual components: `python police_runtime.py`
- Check API health: `curl http://localhost:5000/health`

---

**Remember**: This system is designed to support the mental wellness of police personnel. Always prioritize their privacy and well-being in any modifications or deployments.