Toy bounded from flutter app to agent but not fetched in app

This commit is contained in:
AbrahamCFT360 2025-08-27 18:53:51 +05:30
parent 06a9378fb6
commit 8bcd7c8719
19 changed files with 0 additions and 2766 deletions

View file

@ -1,441 +0,0 @@
# Xiaozhi ESP32 Device Connectivity Guide
## Table of Contents
- [Overview](#overview)
- [Device Activation Process](#device-activation-process)
- [MQTT Communication](#mqtt-communication)
- [UDP Communication](#udp-communication)
- [WebSocket Communication](#websocket-communication)
- [Network Architecture](#network-architecture)
- [Troubleshooting](#troubleshooting)
## Overview
The Xiaozhi ESP32 Server supports multiple communication protocols for device connectivity:
- **HTTP/HTTPS**: For OTA updates and initial device registration
- **MQTT**: For real-time bidirectional communication
- **UDP**: For low-latency audio streaming
- **WebSocket**: For persistent real-time connections
## Device Activation Process
### 1. Initial Connection Flow
```mermaid
sequenceDiagram
participant ESP32 as ESP32 Device
participant OTA as OTA Endpoint (8002)
participant Redis as Redis Cache
participant Web as Web Dashboard
participant User as User
ESP32->>OTA: POST /xiaozhi/ota
Note over ESP32,OTA: Headers: device-id (MAC address)
Note over ESP32,OTA: Body: firmware info, board type
OTA->>Redis: Check if device registered
alt Device Not Registered
OTA->>Redis: Generate 6-digit code
Redis-->>OTA: Store activation code
OTA-->>ESP32: Return activation code + MQTT credentials
ESP32->>ESP32: Display code on screen/log
User->>Web: Enter activation code
Web->>Redis: Validate code
Web->>Web: Register device to user
else Device Registered
OTA-->>ESP32: Return MQTT credentials + config
end
```
### 2. Activation Code Generation
**Location**: `DeviceServiceImpl.java:buildActivation()`
The activation process works as follows:
1. **Device Makes OTA Request**:
```http
POST http://192.168.1.105:8002/xiaozhi/ota
Headers:
device-id: AA:BB:CC:DD:EE:FF
Body:
{
"application": {"version": "1.0.0"},
"board": {"type": "esp32s3"},
"chip_model_name": "ESP32-S3"
}
```
2. **Server Generates Activation Code**:
```java
// 6-digit random code
String newCode = RandomUtil.randomNumbers(6);
// Store in Redis with two keys:
// 1. Device data key
String dataKey = "ota:device:" + deviceId;
redisUtils.set(dataKey, deviceData);
// 2. Code lookup key (for validation)
String codeKey = "ota:activation:code:" + newCode;
redisUtils.set(codeKey, deviceId);
```
3. **Response to Device**:
```json
{
"activation": {
"code": "141966",
"message": "http://dashboard.url\n141966",
"challenge": "AA:BB:CC:DD:EE:FF"
},
"mqtt": {
"endpoint": "192.168.1.105:1883",
"client_id": "GID_test@@@AA_BB_CC_DD_EE_FF@@@uuid",
"username": "base64_encoded_user_data",
"password": "hmac_sha256_signature",
"publish_topic": "device-server",
"subscribe_topic": "null"
}
}
```
4. **User Activation**:
- User sees code on device display/logs
- Opens web dashboard
- Enters 6-digit code
- Device is bound to user account
## MQTT Communication
### MQTT Configuration
**Default Settings**:
- **Broker**: 192.168.1.105 (configurable)
- **Port**: 1883
- **Protocol**: MQTT 3.1.1
### MQTT Credential Generation
**Location**: `DeviceServiceImpl.java:buildMqttCredentials()`
The MQTT authentication uses a secure HMAC-SHA256 signature:
```java
// Client ID Format
String clientId = "GID_test@@@{mac_address}@@@{uuid}";
// Example: GID_test@@@AA_BB_CC_DD_EE_FF@@@550e8400-e29b-41d4-a716-446655440000
// Username (Base64 encoded JSON)
String userData = {"ip": "client_ip_address"};
String username = Base64.encode(userData);
// Password (HMAC-SHA256 signature)
String content = clientId + "|" + username;
String password = Base64.encode(
HMAC_SHA256(content, signature_key)
);
```
### MQTT Topics
- **Device to Server**: `device-server`
- **Server to Device**: Device subscribes to personalized topics
- **Message Format**: JSON payloads
### MQTT Message Flow
```mermaid
graph LR
A[ESP32 Device] -->|Publish| B[device-server topic]
B --> C[MQTT Broker]
C --> D[Xiaozhi Server]
D -->|Process & Respond| E[Device-specific topic]
E --> C
C -->|Subscribe| A
```
## UDP Communication
### UDP Audio Streaming
**Configuration**:
- **Port**: 8884
- **Purpose**: Real-time audio streaming
- **Protocol**: Custom binary protocol
### UDP Packet Structure
```
+------------------+------------------+------------------+
| Device ID (6B) | Sequence (4B) | Audio Data (nB) |
+------------------+------------------+------------------+
```
### Audio Parameters
```yaml
audio_params:
format: opus # Audio codec
sample_rate: 16000 # Hz
channels: 1 # Mono
frame_duration: 60 # ms
```
### UDP Flow for Audio
1. **Device captures audio** from microphone
2. **Encodes with Opus** codec
3. **Sends UDP packets** to server:8884
4. **Server processes** audio (ASR/Speech recognition)
5. **Response sent** via MQTT or WebSocket
## WebSocket Communication
### WebSocket Endpoint
**URL Format**: `ws://{server_ip}:{port}/xiaozhi/v1/`
### Connection Flow
```javascript
// Client connection example
const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/');
ws.onopen = () => {
// Send authentication
ws.send(JSON.stringify({
type: 'auth',
device_id: 'AA:BB:CC:DD:EE:FF',
token: 'device_token'
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// Handle server messages
};
```
## Network Architecture
### Complete System Architecture
```mermaid
graph TB
subgraph "ESP32 Devices"
D1[Device 1]
D2[Device 2]
D3[Device N]
end
subgraph "Communication Layer"
HTTP[HTTP/8002<br/>OTA & Activation]
WS[WebSocket/8000<br/>Real-time Control]
MQTT[MQTT/1883<br/>Commands & Status]
UDP[UDP/8884<br/>Audio Stream]
end
subgraph "Backend Services"
JAVA[Manager API<br/>Port 8002]
PY[Xiaozhi Server<br/>Port 8000/8003]
REDIS[Redis Cache<br/>Activation Codes]
DB[(PostgreSQL<br/>Device Registry)]
end
subgraph "Frontend"
WEB[Web Dashboard<br/>Device Management]
MOBILE[Mobile App<br/>Device Control]
end
D1 & D2 & D3 -.->|Initial Setup| HTTP
D1 & D2 & D3 -->|Status Updates| MQTT
D1 & D2 & D3 -->|Audio Stream| UDP
D1 & D2 & D3 <-->|Control| WS
HTTP --> JAVA
WS --> PY
MQTT --> PY
UDP --> PY
JAVA <--> REDIS
JAVA <--> DB
PY <--> REDIS
PY <--> DB
WEB --> JAVA
MOBILE --> JAVA
```
### Port Summary
| Service | Port | Protocol | Purpose |
|---------|------|----------|---------|
| Manager API | 8002 | HTTP | Device OTA, Activation |
| Xiaozhi Server WS | 8000 | WebSocket | Real-time communication |
| Xiaozhi Server HTTP | 8003 | HTTP | API endpoints, MCP |
| MQTT Broker | 1883 | MQTT | Message broker |
| UDP Audio | 8884 | UDP | Audio streaming |
| Web Dashboard | 3000 | HTTP | User interface |
## Configuration Files
### 1. Server Configuration (`config.yaml`)
```yaml
server:
ip: 0.0.0.0
port: 8000 # WebSocket port
http_port: 8003 # HTTP API port
mqtt_gateway:
enabled: true
broker: 192.168.1.105
port: 1883
udp_port: 8884
```
### 2. Manager API Configuration
```yaml
manager-api:
url: http://192.168.1.105:8002/xiaozhi
secret: your-secret-key
```
## Troubleshooting
### Common Issues and Solutions
#### 1. Device Not Receiving Activation Code
**Symptom**: Device connects but no activation code generated
**Check**:
- Verify device is calling correct OTA endpoint (port 8002, not 8003)
- Check Redis is running and accessible
- Verify device-id header is present in request
**Solution**:
```bash
# Check Redis for activation codes
redis-cli
> KEYS ota:activation:code:*
> GET ota:device:AA:BB:CC:DD:EE:FF
```
#### 2. MQTT Connection Failed
**Symptom**: Device cannot connect to MQTT broker
**Check**:
- MQTT broker is running on port 1883
- Firewall allows MQTT traffic
- Credentials are correctly generated
**Debug**:
```bash
# Test MQTT connection
mosquitto_sub -h 192.168.1.105 -p 1883 -t "device-server" -v
# Check MQTT logs
tail -f /var/log/mosquitto/mosquitto.log
```
#### 3. UDP Audio Not Working
**Symptom**: Audio from device not received
**Check**:
- UDP port 8884 is open
- Audio format matches configuration (Opus, 16kHz, mono)
- Network allows UDP traffic
**Test**:
```python
# Simple UDP listener test
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 8884))
while True:
data, addr = sock.recvfrom(4096)
print(f"Received {len(data)} bytes from {addr}")
```
#### 4. WebSocket Connection Drops
**Symptom**: WebSocket disconnects frequently
**Check**:
- Keepalive/ping-pong implemented
- Proxy/load balancer timeout settings
- Network stability
**Configuration**:
```javascript
// Client-side keepalive
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({type: 'ping'}));
}
}, 30000); // Every 30 seconds
```
### Debug Logs
Enable debug logging for different components:
```yaml
log:
log_level: DEBUG
module_levels:
OTA: DEBUG
MQTT: DEBUG
UDP: DEBUG
WebSocket: DEBUG
```
### Testing Tools
1. **Test OTA Endpoint**:
```bash
curl -X POST http://192.168.1.105:8002/xiaozhi/ota \
-H "device-id: AA:BB:CC:DD:EE:FF" \
-H "Content-Type: application/json" \
-d '{"application":{"version":"1.0.0"}}'
```
2. **Test MQTT Publish**:
```bash
mosquitto_pub -h 192.168.1.105 -p 1883 \
-t "device-server" \
-m '{"device_id":"AA:BB:CC:DD:EE:FF","message":"test"}'
```
3. **Monitor WebSocket**:
```javascript
// Browser console
const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/');
ws.onmessage = (e) => console.log('Received:', e.data);
ws.onerror = (e) => console.error('Error:', e);
```
## Security Considerations
1. **MQTT Authentication**: Uses HMAC-SHA256 signatures
2. **Activation Codes**: 6-digit codes with Redis TTL
3. **Device IDs**: MAC addresses as unique identifiers
4. **Network Security**: Consider using TLS/SSL for production
5. **API Keys**: Stored securely in environment variables
## Performance Optimization
1. **MQTT QoS**: Use QoS 0 for audio commands, QoS 1 for critical messages
2. **UDP Buffer**: Increase system UDP buffer for audio streaming
3. **WebSocket**: Implement connection pooling for multiple devices
4. **Redis**: Set appropriate TTL for activation codes (default: 5 minutes)
## Contact & Support
For issues or questions:
- GitHub Issues: [your-repo-url]
- Documentation: This guide
- Logs: Check `/tmp/xiaozhi-server.log` for detailed debugging

View file

@ -1,179 +0,0 @@
# English-Only Sherpa-ONNX ASR Models Comparison
## ✅ **VERIFIED WORKING English-Only Models from csukuangfj**
### 🏆 **RECOMMENDED: Zipformer English (2023-04-01)**
- **Model ID**: `csukuangfj/sherpa-onnx-zipformer-en-2023-04-01`
- **Config Name**: `SherpaZipformerEN`
- **Size**: ~65MB
- **Type**: Offline processing with good speed
- **Accuracy**: Excellent for English
- **Speed**: Very fast
- **Best for**: General English ASR, good balance
- **Pros**:
- Proven working model
- Excellent English accuracy
- Good processing speed
- Reliable performance
### 📚 **LARGE VOCABULARY: Zipformer Gigaspeech English** ⭐ RECOMMENDED
- **Model Source**: GitHub (k2-fsa/sherpa-onnx releases)
- **Config Name**: `SherpaZipformerGigaspeechEN`
- **Size**: ~120MB
- **Type**: Offline processing (Zipformer architecture)
- **Training**: GigaSpeech dataset (10,000+ hours English audio)
- **Accuracy**: Excellent (trained on massive English dataset)
- **Speed**: Very Good (optimized Zipformer)
- **Best for**: Kids, conversational AI, large vocabulary
- **Pros**:
- ✅ **100% English-only** (no multilingual overhead)
- 📚 **Massive vocabulary** (podcasts, audiobooks, YouTube)
- 👶 **Perfect for kids** (YouTube training = informal speech)
- 🚀 **Fast processing** (Zipformer architecture)
- 👥 **Excellent multi-client** support
- 🎯 **Latest training** (2023 data)
### 🔄 **ALTERNATIVE: Paraformer English**
- **Model ID**: `csukuangfj/sherpa-onnx-paraformer-en-2023-10-24`
- **Config Name**: `SherpaParaformerEN`
- **Size**: ~50MB
- **Type**: Offline processing
- **Accuracy**: Very good for English
- **Speed**: Fast
- **Best for**: Alternative architecture, good performance
- **Pros**:
- Different architecture (Paraformer vs Zipformer)
- Good accuracy
- Moderate size
- Reliable fallback option
### 🎯 **HIGHEST ACCURACY: Whisper Models**
#### Whisper Small English
- **Model ID**: `csukuangfj/sherpa-onnx-whisper-small.en`
- **Config Name**: `SherpaWhisperSmallEN`
- **Size**: ~244MB
- **Accuracy**: Excellent
- **Speed**: Moderate
- **Best for**: High accuracy requirements
#### Whisper Base English
- **Model ID**: `csukuangfj/sherpa-onnx-whisper-base.en`
- **Config Name**: `SherpaWhisperBaseEN`
- **Size**: ~74MB
- **Accuracy**: Very good
- **Speed**: Good
- **Best for**: General purpose with good accuracy
#### Whisper Tiny English
- **Model ID**: `csukuangfj/sherpa-onnx-whisper-tiny.en`
- **Config Name**: `SherpaWhisperTinyEN`
- **Size**: ~39MB
- **Accuracy**: Good
- **Speed**: Fast
- **Best for**: Quick processing with acceptable accuracy
## Performance Comparison
| Model | Size | Speed | Accuracy | Multi-Client | Best Use Case |
|-------|------|-------|----------|--------------|---------------|
| **Zipformer English (2023-04-01)** | 65MB | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | **General purpose** |
| **Zipformer Gigaspeech** | 120MB | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | **Large vocabulary** |
| **Paraformer English** | 50MB | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ✅ | **Alternative arch** |
| **Whisper Small.en** | 244MB | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | **High accuracy** |
| **Whisper Base.en** | 74MB | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ✅ | **Balanced** |
| **Whisper Tiny.en** | 39MB | ⭐⭐⭐⭐ | ⭐⭐⭐ | ✅ | **Fastest** |
## Usage Instructions
### 1. **For General English ASR** (Recommended)
```yaml
selected_module:
ASR: SherpaZipformerEN
```
### 2. **For Large Vocabulary/Technical Terms**
```yaml
selected_module:
ASR: SherpaZipformerGigaspeechEN
```
### 3. **For Highest Accuracy**
```yaml
selected_module:
ASR: SherpaWhisperSmallEN
```
### 4. **For Fastest Processing**
```yaml
selected_module:
ASR: SherpaWhisperTinyEN
```
## Technical Details
### Zipformer Models
- **Architecture**: Zipformer (optimized Transformer)
- **Training**: LibriSpeech English dataset
- **Features**:
- Streaming capability
- Low latency
- Optimized for English phonemes
- Better performance on English accents
### Whisper Models
- **Architecture**: Transformer encoder-decoder
- **Training**: Large-scale multilingual dataset (English subset)
- **Features**:
- Very high accuracy
- Robust to noise
- Good with various English accents
- Offline processing only
### Conformer Models
- **Architecture**: Conformer (Convolution + Transformer)
- **Training**: LibriSpeech English dataset
- **Features**:
- Good balance of local and global features
- Reliable performance
- Moderate resource usage
## Migration from Multilingual Model
To switch from the current multilingual model to English-only:
1. **Update config.yaml**:
```yaml
selected_module:
ASR: SherpaZipformerStreamingEN # or your preferred model
```
2. **Benefits of switching**:
- 🚀 **Faster processing**: English-only models are optimized
- 💾 **Smaller size**: Reduced model complexity
- 🎯 **Better accuracy**: Specialized for English patterns
- ⚡ **Lower latency**: Especially with streaming models
- 💰 **Less memory**: Reduced resource usage
3. **The system will automatically**:
- Download the new model files
- Initialize the correct model type
- Handle the different file structures
## Conclusion
**For most use cases, we recommend `SherpaZipformerGigaspeechEN`** as it provides:
- **Excellent English accuracy** (trained on 10k+ hours)
- **Very fast processing** (optimized Zipformer)
- **Massive vocabulary** (GigaSpeech dataset)
- **Perfect for kids** (YouTube + podcast training)
- **Reasonable model size** (~120MB)
- **100% English-only** (no multilingual overhead)
- **Optimized for conversational speech**
- **Works perfectly with multiple concurrent clients**
This model is specifically designed for English and will significantly outperform the multilingual model for English-only applications.
## ✅ **Fixed Model Availability Issue**
The original streaming models I mentioned don't exist on ModelScope. The models listed above are **verified working** and available for download. They will handle multiple concurrent clients effectively as explained in the concurrency analysis.

View file

@ -1,205 +0,0 @@
# 🎯 English-Only ASR Setup Guide
Transform your bot into a lightning-fast English conversation partner! This guide helps you set up the best English-only ASR models for 3x faster processing.
## 🚀 Quick Start (30 seconds)
```bash
# Run the automated setup
python setup_english_asr.py
# Start your server
python main/xiaozhi-server/app.py
```
That's it! Your bot now has supercharged English processing.
## 🏆 Available English Models
### 1. **Gigaspeech English** (RECOMMENDED for Kids)
- **Best for**: Children's companion bots, conversational AI
- **Training**: 10,000+ hours (podcasts, YouTube, audiobooks)
- **Size**: ~335MB
- **Speed**: ⭐⭐⭐⭐⭐ Very Fast
- **Vocabulary**: ⭐⭐⭐⭐⭐ Massive
- **Multi-client**: Perfect for multiple kids simultaneously
### 2. **Whisper Tiny English** (FASTEST)
- **Best for**: Quick responses, resource-constrained devices
- **Size**: ~153MB
- **Speed**: ⭐⭐⭐⭐⭐ Fastest
- **Vocabulary**: ⭐⭐⭐ Good
- **Perfect for**: Simple conversations, embedded devices
### 3. **Whisper Base English** (BALANCED)
- **Best for**: General purpose English applications
- **Size**: ~74MB
- **Speed**: ⭐⭐⭐⭐ Fast
- **Vocabulary**: ⭐⭐⭐⭐ Very Good
- **Perfect for**: Most English-only applications
### 4. **Whisper Small English** (HIGHEST ACCURACY)
- **Best for**: Professional applications, complex speech
- **Size**: ~244MB
- **Speed**: ⭐⭐⭐ Good
- **Vocabulary**: ⭐⭐⭐⭐⭐ Excellent
- **Perfect for**: High-accuracy requirements
## 🎈 Perfect for Kids Bots
The **Gigaspeech model** is specially trained on YouTube content, making it perfect for understanding:
- Creative and playful language
- Incomplete sentences ("I want... um... can you...")
- Modern slang and expressions
- Multiple kids talking simultaneously
## ⚡ Performance Benefits
| Feature | Multilingual | English-Only | Improvement |
|---------|-------------|--------------|-------------|
| **Processing Speed** | 1.5s | 0.5s | **3x faster** |
| **Memory Usage** | 500MB | 200MB | **60% less** |
| **Accuracy (English)** | 85% | 95% | **10% better** |
| **Vocabulary** | Limited | Massive | **5x larger** |
## 🔧 Manual Setup
If you prefer manual configuration:
### Step 1: Edit Config
```yaml
# In main/xiaozhi-server/data/.config.yaml
selected_module:
ASR: SherpaZipformerGigaspeechEN # or your preferred model
```
### Step 2: Add Model Configuration
```yaml
ASR:
SherpaZipformerGigaspeechEN:
type: sherpa_onnx_local
model_dir: models/sherpa-onnx-zipformer-gigaspeech-2023-12-12
model_type: zipformer
output_dir: tmp/
```
### Step 3: Start Server
```bash
python main/xiaozhi-server/app.py
```
## 🔽 Manual Downloads
If automatic download fails:
### Gigaspeech Model
```bash
python download_gigaspeech_manual.py
```
### Whisper Models
Whisper models download automatically from Hugging Face - no manual steps needed!
## 👥 Multiple Client Support
All English models support multiple concurrent clients:
| Concurrent Users | Performance | Recommended Model |
|------------------|-------------|-------------------|
| **1-5 users** | Excellent | Any model |
| **6-10 users** | Very Good | Gigaspeech or Whisper Base |
| **11-20 users** | Good | Gigaspeech (best efficiency) |
| **20+ users** | Fair | Consider load balancing |
## 🎯 Use Case Recommendations
### 👶 **Kids Companion Bot**
```yaml
ASR: SherpaZipformerGigaspeechEN
```
- Handles creative language
- YouTube training = understands kid speech
- Multiple kids simultaneously
- Fast responses keep engagement
### ⚡ **Quick Response Bot**
```yaml
ASR: SherpaWhisperTinyEN
```
- Fastest processing
- Small memory footprint
- Perfect for simple interactions
### 🎓 **Educational Bot**
```yaml
ASR: SherpaWhisperSmallEN
```
- Highest accuracy
- Best for learning applications
- Handles complex vocabulary
### 🏢 **Business Bot**
```yaml
ASR: SherpaWhisperBaseEN
```
- Professional accuracy
- Balanced performance
- Reliable for customer service
## 🛠️ Troubleshooting
### Model Download Issues
```bash
# Check your configuration
python check_config.py
# Fix configuration automatically
python fix_asr_config.py
# Manual Gigaspeech download
python download_gigaspeech_manual.py
```
### Performance Issues
- **Slow processing**: Switch to Whisper Tiny
- **Low accuracy**: Switch to Whisper Small
- **Memory issues**: Use Whisper Tiny or Base
- **Multiple clients**: Use Gigaspeech (most efficient)
## 📊 Benchmarks
Tested on typical hardware (8GB RAM, 4-core CPU):
| Model | Load Time | Processing Time | Memory Usage | Concurrent Users |
|-------|-----------|-----------------|--------------|------------------|
| **Gigaspeech** | 15s | 0.3s | 250MB | 15+ |
| **Whisper Tiny** | 5s | 0.2s | 180MB | 20+ |
| **Whisper Base** | 8s | 0.4s | 220MB | 12+ |
| **Whisper Small** | 12s | 0.8s | 300MB | 8+ |
## 🎉 Success Stories
> "Switched to Gigaspeech for our kids' learning bot. Response time went from 2 seconds to 0.3 seconds. Kids love the instant responses!" - *Educational App Developer*
> "Whisper Tiny handles 25 concurrent users perfectly. Memory usage dropped by 60%." - *IoT Device Manufacturer*
> "The vocabulary improvement is incredible. Our bot now understands creative kid language perfectly." - *Children's Entertainment Company*
## 🔗 Additional Resources
- [Sherpa-ONNX Documentation](https://k2-fsa.github.io/sherpa/onnx/)
- [Whisper Model Details](https://github.com/openai/whisper)
- [GigaSpeech Dataset](https://github.com/SpeechColab/GigaSpeech)
- [Performance Optimization Guide](./TROUBLESHOOTING.md)
## 💡 Pro Tips
1. **Start with Gigaspeech** - it's the best all-around choice
2. **Use Whisper Tiny** for embedded devices or high concurrency
3. **Monitor memory usage** - switch models if needed
4. **Test with your target audience** - kids vs adults have different patterns
5. **Consider load balancing** for 20+ concurrent users
---
🎯 **Ready to supercharge your English bot?** Run `python setup_english_asr.py` and experience the difference!

View file

@ -1,83 +0,0 @@
# English ASR Setup Guide
## ✅ **FIXED: Working English-Only Models**
Your server is now configured to use **verified working** English-only models that support multiple concurrent clients.
## 🚀 **Quick Start**
### 1. **Current Configuration**
Your server is set to use: `SherpaWhisperTinyEN` (fastest, smallest English model)
### 2. **Available Models** (all working)
| Model | Config Name | Size | Speed | Best For |
|-------|-------------|------|-------|----------|
| **Whisper Tiny EN** | `SherpaWhisperTinyEN` | 39MB | ⭐⭐⭐⭐⭐ | **Fastest** |
| **Whisper Base EN** | `SherpaWhisperBaseEN` | 74MB | ⭐⭐⭐⭐ | **Balanced** |
| **Whisper Small EN** | `SherpaWhisperSmallEN` | 244MB | ⭐⭐⭐ | **High Accuracy** |
| **Zipformer EN** | `SherpaZipformerEN` | 65MB | ⭐⭐⭐⭐ | **Good Balance** |
### 3. **To Change Models**
Edit `main/xiaozhi-server/data/.config.yaml`:
```yaml
selected_module:
ASR: SherpaWhisperBaseEN # Change this line
```
## 🔧 **Enhanced Download System**
The system now supports both:
- **Hugging Face Hub** (more reliable)
- **ModelScope** (fallback)
### Install Hugging Face Hub (Recommended)
```bash
python install_huggingface.py
```
## ✅ **Multiple Client Support**
All these models **WILL work with multiple concurrent clients** because:
1. **Shared Model Instance**: One model serves all clients efficiently
2. **Per-Client Streams**: Each client gets isolated processing
3. **Thread-Safe**: Concurrent processing without conflicts
4. **Session Isolation**: Each client's audio is processed separately
## 🎯 **Recommendations**
### For Your Kid Companion Bot:
- **Start with**: `SherpaWhisperTinyEN` (fastest, good for kids)
- **Upgrade to**: `SherpaWhisperBaseEN` (better accuracy)
- **Best quality**: `SherpaWhisperSmallEN` (highest accuracy)
### Performance with Multiple Kids:
- **1-5 kids**: Excellent performance
- **6-10 kids**: Very good performance
- **10+ kids**: Good performance (may need hardware upgrade)
## 🚀 **Start Your Server**
Your server should now start successfully with:
```bash
python app.py
```
The system will automatically:
1. Download the English model files
2. Initialize the ASR provider
3. Handle multiple concurrent connections
4. Process English speech efficiently
## 🎉 **Benefits of English-Only Models**
- **3x faster** processing than multilingual
- **50% smaller** memory footprint
- **Better accuracy** for English speech
- **Optimized** for English phonemes and accents
- **Perfect** for your kid companion use case
Your Cheeko bot is now ready to handle multiple kids speaking English simultaneously! 🎈

View file

@ -1,174 +0,0 @@
# SiliconFlow TTS with ElevenLabs Fallback Implementation
## Overview
Enhanced the SiliconFlow TTS provider with automatic ElevenLabs fallback for maximum reliability. If SiliconFlow fails for any reason, the system automatically switches to ElevenLabs without interrupting the user experience.
## Implementation Details
### 1. **Fallback Logic Flow**
```
Text Input → SiliconFlow TTS → Success? → Return Audio
↓ (Fail)
ElevenLabs TTS → Success? → Return Audio
↓ (Fail)
Return Error
```
### 2. **Code Changes**
#### **Enhanced Constructor**
```python
# Initialize ElevenLabs fallback if configured
self.fallback_provider = None
fallback_config = config.get("fallback", {})
if fallback_config.get("enabled", True) and fallback_config.get("elevenlabs"):
try:
self.fallback_provider = ElevenLabsProvider(fallback_config["elevenlabs"], delete_audio_file)
logger.bind(tag=TAG).info("ElevenLabs fallback provider initialized")
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to initialize ElevenLabs fallback: {e}")
```
#### **Fallback TTS Method**
```python
async def text_to_speak(self, text, output_file):
# Try SiliconFlow first
try:
return await self._siliconflow_tts(text, output_file)
except Exception as e:
logger.bind(tag=TAG).warning(f"SiliconFlow TTS failed: {str(e)}")
# Try ElevenLabs fallback if available
if self.fallback_provider:
logger.bind(tag=TAG).info("Attempting ElevenLabs fallback...")
try:
return await self.fallback_provider.text_to_speak(text, output_file)
except Exception as fallback_error:
logger.bind(tag=TAG).error(f"ElevenLabs fallback also failed: {str(fallback_error)}")
raise Exception(f"Both SiliconFlow and ElevenLabs failed. SiliconFlow: {str(e)}, ElevenLabs: {str(fallback_error)}")
else:
# No fallback available, re-raise original error
raise
```
### 3. **Configuration Structure**
```yaml
siliconflow:
# Primary SiliconFlow settings
access_token: YOUR_SILICONFLOW_TOKEN
model: FunAudioLLM/CosyVoice2-0.5B
voice: diana
response_format: mp3
speed: 1.0
gain: 0
output_dir: tmp/
# Fallback configuration
fallback:
enabled: true # Enable/disable fallback
elevenlabs:
api_key: YOUR_ELEVENLABS_API_KEY
voice_id: XJ2fW4ybq7HouelYYGcL # Rachel voice
model_id: eleven_turbo_v2_5
stability: 0.75
similarity_boost: 0.75
style: 0.0
use_speaker_boost: true
output_format: mp3_44100_128
optimize_streaming_latency: 0
output_dir: tmp/
```
## Fallback Scenarios
### ✅ **When Fallback Triggers**
- SiliconFlow API returns 401 (Invalid token)
- SiliconFlow API returns 429 (Rate limit exceeded)
- SiliconFlow API returns 500+ (Server errors)
- Network timeout to SiliconFlow
- Any other SiliconFlow API failure
### 🔄 **Fallback Process**
1. **Primary Attempt**: SiliconFlow CosyVoice with diana voice
2. **Log Warning**: Record SiliconFlow failure reason
3. **Fallback Attempt**: ElevenLabs with Rachel voice
4. **Success Logging**: Record which provider succeeded
5. **Return Audio**: Transparent to calling application
### 📊 **Error Handling**
- **SiliconFlow Only Fails**: Use ElevenLabs, return success
- **Both Fail**: Return combined error message
- **No Fallback Configured**: Return original SiliconFlow error
## Voice Mapping
| SiliconFlow Voice | ElevenLabs Fallback | Description |
|-------------------|-------------------|-------------|
| `diana` | Rachel (`XJ2fW4ybq7HouelYYGcL`) | Natural female voice |
| `alex` | Rachel (`XJ2fW4ybq7HouelYYGcL`) | Fallback to female voice |
| `bella` | Rachel (`XJ2fW4ybq7HouelYYGcL`) | Consistent female voice |
## Testing
### **Test Scripts**
1. `test_siliconflow_tts.py` - Basic functionality
2. `test_fallback_tts.py` - Fallback functionality
3. `test_voice_format.py` - Voice format handling
### **Test Scenarios**
```bash
# Test normal operation
python test_siliconflow_tts.py
# Test fallback with invalid token
python test_fallback_tts.py
# Test voice format handling
python test_voice_format.py
```
## Benefits
### 🛡️ **Reliability**
- **99.9% Uptime**: Even if one service fails, the other continues
- **Automatic Recovery**: No manual intervention required
- **Transparent Operation**: Users don't notice provider switches
### ⚡ **Performance**
- **Primary Provider**: SiliconFlow (fast, cost-effective)
- **Backup Provider**: ElevenLabs (reliable, high-quality)
- **Minimal Latency**: Only adds delay when primary fails
### 📈 **Monitoring**
- **Detailed Logging**: Track which provider is used
- **Error Tracking**: Monitor failure rates
- **Performance Metrics**: Compare provider response times
## Configuration Options
### **Enable/Disable Fallback**
```yaml
fallback:
enabled: false # Disable fallback completely
```
### **Fallback Only Mode**
```yaml
# Use invalid SiliconFlow token to force ElevenLabs
access_token: "force_fallback"
fallback:
enabled: true
elevenlabs:
# ... ElevenLabs config ...
```
## Production Recommendations
1. **Always Enable Fallback**: Set `fallback.enabled: true`
2. **Valid API Keys**: Ensure both SiliconFlow and ElevenLabs keys are valid
3. **Monitor Logs**: Track which provider is being used
4. **Test Regularly**: Run fallback tests to ensure both providers work
5. **Voice Consistency**: Choose similar voices for seamless experience
The fallback system ensures your TTS functionality remains reliable and available even when individual providers experience issues.

View file

@ -1,218 +0,0 @@
# Mobile App Integration with Java Backend
## Overview
This document describes how the Flutter mobile app integrates with both Supabase Authentication and the Java backend for user registration and authentication.
## Registration Flow
### 1. User Sign Up Process
1. **User enters email and password** in the Flutter app (`auth_screen.dart`)
2. **Sign up with Supabase** - User account is created in Supabase Authentication
3. **Password temporarily stored** - Password is saved in SharedPreferences for Java backend registration
4. **Email verification sent** - Supabase sends OTP to user's email
5. **User verifies email** - User enters OTP in verification screen
6. **Java backend registration** - After successful verification, user is automatically registered in Java backend
7. **Clean up** - Temporary password is removed from SharedPreferences
8. **Navigate to profile setup** - User proceeds to complete their profile
### 2. Sign In Process
- User signs in with Supabase credentials
- Java backend login is optional (only if accessing Java backend APIs)
- Token from Java backend can be stored for subsequent API calls
## Implementation Details
### Files Modified
#### 1. **JavaAuthService** (`lib/services/java_auth_service.dart`)
New service created to handle Java backend authentication:
- `registerUser()` - Registers user in Java backend
- `login()` - Logs into Java backend (optional)
- `getCaptcha()` - Returns bypass token for mobile apps
- `checkUserExists()` - Checks if user exists in Java backend
#### 2. **Email Verification Screen** (`lib/screens/email_verification_screen.dart`)
Modified to include Java backend registration after email verification:
```dart
// After successful Supabase verification
final javaAuthService = JavaAuthService();
final password = prefs.getString('temp_password_${widget.email}');
if (password != null) {
await javaAuthService.registerUser(
email: widget.email,
password: password,
);
}
```
#### 3. **Auth Screen** (`lib/screens/auth_screen.dart`)
Modified to temporarily store password:
```dart
// Store password for Java backend registration
final prefs = await SharedPreferences.getInstance();
await prefs.setString('temp_password_$email', password);
```
#### 4. **Java Backend Captcha Service** (`CaptchaServiceImpl.java`)
Modified to accept mobile app bypass token:
```java
if ("MOBILE_APP_BYPASS".equals(code)) {
return true; // Mobile apps bypass captcha
}
```
## Configuration
### Update Base URL
In `lib/services/java_auth_service.dart`, update the base URL:
```dart
// For local development
static const String baseUrl = 'http://localhost:8002/xiaozhi';
// For production (replace with your server URL)
static const String baseUrl = 'https://your-server.com/xiaozhi';
```
### For iOS (local development)
If testing on iOS simulator with localhost:
```dart
static const String baseUrl = 'http://127.0.0.1:8002/xiaozhi';
```
### For Android (local development)
If testing on Android emulator:
```dart
static const String baseUrl = 'http://10.0.2.2:8002/xiaozhi';
```
### For physical devices (local development)
Use your machine's IP address:
```dart
static const String baseUrl = 'http://192.168.1.240:8002/xiaozhi';
```
## Security Considerations
### 1. Captcha Bypass
The current implementation uses a simple bypass token (`MOBILE_APP_BYPASS`) for mobile apps. In production, consider:
- Adding API key validation
- Implementing device fingerprinting
- Using OAuth2 or JWT tokens
- Rate limiting by device/IP
### 2. Password Storage
Passwords are temporarily stored in SharedPreferences. Consider:
- Using Flutter Secure Storage for sensitive data
- Encrypting the password before storage
- Clearing the password immediately after use
### 3. HTTPS
Always use HTTPS in production:
- Update all URLs to use `https://`
- Implement certificate pinning for additional security
## API Endpoints Used
### Registration
```bash
POST /xiaozhi/user/register
{
"username": "user@example.com",
"password": "password123",
"captcha": "MOBILE_APP_BYPASS",
"captchaId": "uuid-here"
}
```
### Login (Optional)
```bash
POST /xiaozhi/user/login
{
"username": "user@example.com",
"password": "password123",
"captcha": "MOBILE_APP_BYPASS",
"captchaId": "uuid-here"
}
```
## Testing
### 1. Run Flutter App
```bash
cd flutter-mobile-app
flutter pub get
flutter run
```
### 2. Test Registration Flow
1. Create new account with email/password
2. Check console logs for:
- "✅ User registered in both Supabase and Java backend"
3. Verify user exists in both:
- Supabase Dashboard
- MySQL database (sys_user table)
### 3. Common Issues
#### Issue: Connection refused
**Solution**: Check that Java backend is running and accessible from your device
#### Issue: Captcha validation failed
**Solution**: Ensure CaptchaServiceImpl.java has the bypass code
#### Issue: User already exists
**Solution**: This is handled gracefully - the app will proceed even if user exists in Java backend
## Future Improvements
1. **Token Management**
- Implement proper token storage and refresh
- Use Java backend token for protected APIs
2. **Error Handling**
- Add retry logic for network failures
- Implement offline mode support
3. **Security Enhancements**
- Add device-specific tokens
- Implement biometric authentication
- Add 2FA support
4. **Profile Sync**
- Sync user profiles between Supabase and Java backend
- Handle profile updates across both systems
## Dependencies Added
```yaml
# pubspec.yaml
dependencies:
uuid: ^4.5.1 # For generating UUIDs
shared_preferences: ^2.2.2 # Already existed
```
## Troubleshooting
### Check Java Backend Logs
```bash
tail -f main/manager-api/logs/xiaozhi-esp32-api.log
```
### Test API Directly
```bash
# Test registration endpoint
curl -X POST "http://localhost:8002/xiaozhi/user/register" \
-H "Content-Type: application/json" \
-d '{
"username": "test@example.com",
"password": "password123",
"captcha": "MOBILE_APP_BYPASS",
"captchaId": "test-uuid"
}'
```
### Verify Database Entry
```sql
-- Check if user was created in MySQL
SELECT * FROM sys_user WHERE username = 'test@example.com';
```

View file

@ -1,57 +0,0 @@
Commands to start the servers:
Backend (Spring Boot):
cd main/manager-api
mvn spring-boot:run
Frontend (Vue.js):
cd main/manager-web
npm run serve
The backend runs on port 8002 at http://localhost:8002/xiaozhi
The frontend runs on port 8001 at http://localhost:8001/
The backend requires Java 21.
Update(main/manager-api/pom.xml)
⎿ Updated main/manager-api/pom.xml with 1 addition and 1 removal
17 <properties>
18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
20 - <java.version>21</java.version>
20 + <java.version>17</java.version>
The getFirst() method is a Java 21 feature.
fix both files to use Java 17 compatible code:
⏺ Update(main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java)
⎿ Updated main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java with 1 addition and 1 removal
66 // 同类固件只保留最新的一条
67 List<OtaEntity> otaList = baseDao.selectList(queryWrapper);
68 if (otaList != null && otaList.size() > 0) {
69 - OtaEntity otaBefore = otaList.getFirst();
69 + OtaEntity otaBefore = otaList.get(0);
There's a syntax error in the Liquibase configuration file. Let me check and fix it:
⏺ Read(main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml)
⎿ Read 249 lines (ctrl+r to expand)
⏺ I see the issue - there's a duplicate id field at line 243. Let me fix this:
⏺ Update(main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml)
⎿ Updated main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml with 2 additions and 1 removal
240 - sqlFile:
241 encoding: utf8
242 path: classpath:db/changelog/202506261637.sql
243 - id: 202506152342
243 + - changeSet:
244 + id: 202507051233
245 author: marlonz
246 changes:
247 - sqlFile:
restart the backend

View file

@ -1,72 +0,0 @@
# SiliconFlow CosyVoice TTS Fixes
## Issues Fixed
### 1. ❌ Invalid Voice Error
**Problem**: API returned "Invalid voice" error for 'diana' voice
**Solution**: Removed voice parameter from API request - the API doesn't support separate voice selection yet
### 2. ✅ Updated API Request Format
**Changes made**:
- Removed `voice` parameter from payload
- Set `stream: True` to match your original example
- Changed `speed` to integer instead of float
### 3. ✅ Updated Configuration
**Before**:
```yaml
siliconflow:
voice: diana # This caused the error
speed: 1.0 # Float value
```
**After**:
```yaml
siliconflow:
# voice parameter removed - not supported by API
speed: 1 # Integer value
```
### 4. ✅ Fixed Test Script
- Improved config file path detection
- Removed voice parameter from fallback config
- Better error handling and output
## Current Working Configuration
```yaml
selected_module:
TTS: siliconflow
TTS:
siliconflow:
access_token: YOUR_TOKEN_HERE
model: FunAudioLLM/CosyVoice2-0.5B
response_format: mp3
speed: 1
gain: 0
output_dir: tmp/
```
## API Request Format (Now Working)
```python
payload = {
"input": text,
"response_format": "mp3",
"stream": True,
"speed": 1,
"gain": 0,
"model": "FunAudioLLM/CosyVoice2-0.5B"
}
# No voice parameter - handled by the model
```
## Test the Fix
Run the test script again:
```bash
python test_siliconflow_tts.py
```
The "Invalid voice" error should now be resolved!

View file

@ -1,139 +0,0 @@
# SiliconFlow CosyVoice TTS Setup Guide
## Quick Setup
### 1. Get Your SiliconFlow API Token
1. Visit [SiliconFlow](https://siliconflow.com)
2. Sign up or log in to your account
3. Navigate to API settings and generate an API token
### 2. Update Configuration
Edit `main/xiaozhi-server/data/.config.yaml`:
```yaml
selected_module:
TTS: siliconflow # ← Change this to use SiliconFlow
TTS:
siliconflow:
access_token: YOUR_ACTUAL_TOKEN_HERE # ← Replace with your token
model: FunAudioLLM/CosyVoice2-0.5B
voice: diana # Default voice (female)
response_format: mp3
speed: 1.0
gain: 0
output_dir: tmp/
```
### 3. Available Voices
- `diana` - Natural female voice (default) → becomes `FunAudioLLM/CosyVoice2-0.5B:diana`
- `alex` - Male voice → becomes `FunAudioLLM/CosyVoice2-0.5B:alex`
- `bella` - Female voice → becomes `FunAudioLLM/CosyVoice2-0.5B:bella`
**Note**: Voice names are automatically prefixed with the model name when making API requests.
### 4. Test the Setup
Run the test scripts:
```bash
# Test basic functionality
python test_siliconflow_tts.py
# Test fallback functionality
python test_fallback_tts.py
```
## Configuration Options
| Parameter | Description | Default | Options |
|-----------|-------------|---------|---------|
| `access_token` | Your SiliconFlow API token | Required | Your API token |
| `model` | CosyVoice model to use | `FunAudioLLM/CosyVoice2-0.5B` | CosyVoice models |
| `voice` | Voice to use for synthesis | `diana` | `diana`, `alex`, `bella` (auto-prefixed with model) |
| `response_format` | Audio output format | `mp3` | `mp3`, `wav` |
| `speed` | Speech speed | `1.0` | `0.5` to `2.0` |
| `gain` | Audio gain adjustment | `0` | Integer values |
| `output_dir` | Directory for audio files | `tmp/` | Any valid path |
| `fallback.enabled` | Enable ElevenLabs fallback | `true` | `true`, `false` |
| `fallback.elevenlabs.*` | ElevenLabs fallback config | See below | ElevenLabs settings |
### ElevenLabs Fallback Configuration
The system includes automatic fallback to ElevenLabs if SiliconFlow fails:
```yaml
siliconflow:
# ... SiliconFlow settings ...
fallback:
enabled: true
elevenlabs:
api_key: YOUR_ELEVENLABS_API_KEY
voice_id: XJ2fW4ybq7HouelYYGcL # Rachel voice
model_id: eleven_turbo_v2_5
stability: 0.75
similarity_boost: 0.75
style: 0.0
use_speaker_boost: true
output_format: mp3_44100_128
optimize_streaming_latency: 0
output_dir: tmp/
```
## Switching Between TTS Providers
To switch back to other TTS providers, change the `selected_module.TTS` value:
```yaml
selected_module:
TTS: elevenlabs # For ElevenLabs
TTS: kittentts # For KittenTTS (local)
TTS: siliconflow # For SiliconFlow CosyVoice
```
## Troubleshooting
### Common Issues:
1. **"SiliconFlow access token is required"**
- Make sure you've added your actual API token to the config
2. **"SiliconFlow TTS request failed: 401"**
- Check that your API token is valid and active
3. **"SiliconFlow TTS request timed out"**
- Check your internet connection
- The API might be experiencing high load
4. **Audio file not generated**
- Ensure the `tmp/` directory exists
- Check file permissions
### Getting Help:
- Check the SiliconFlow API documentation
- Verify your API token is active
- Test with the provided test script first
## Fallback System Benefits
### 🛡️ **Reliability**
- If SiliconFlow is down or returns errors, automatically switches to ElevenLabs
- Ensures your application continues working even if one service fails
- Transparent fallback - users won't notice the switch
### 🔄 **Automatic Recovery**
- No manual intervention required
- Logs which provider was used for debugging
- Graceful error handling
### ⚡ **Performance**
- Tries fastest/preferred provider first (SiliconFlow)
- Falls back to reliable alternative (ElevenLabs)
- Minimal latency impact
## Example Usage
Once configured, the system will:
1. **First**: Try SiliconFlow CosyVoice with diana voice
2. **If SiliconFlow fails**: Automatically use ElevenLabs with Rachel voice
3. **Log the process**: For monitoring and debugging
The fallback is completely transparent to your application.

View file

@ -1,112 +0,0 @@
# SiliconFlow CosyVoice TTS Integration Updates
## Overview
Updated the existing SiliconFlow TTS provider to properly integrate with the CosyVoice API and added 'diana' as the default voice option.
## Changes Made
### 1. Updated TTS Provider (`main/xiaozhi-server/core/providers/tts/siliconflow.py`)
**Key Improvements:**
- ✅ Updated API endpoint to use the correct SiliconFlow URL: `https://api.siliconflow.com/v1/audio/speech`
- ✅ Added proper error handling and logging similar to ElevenLabs implementation
- ✅ Implemented the exact API format you provided with support for:
- `input`: Text to convert to speech
- `response_format`: Audio format (mp3, wav, etc.)
- `stream`: Streaming support (currently set to False)
- `speed`: Speech speed control
- `gain`: Audio gain control
- `model`: CosyVoice model selection
- ✅ Added 'diana' as the default voice
- ✅ Added proper API key validation
- ✅ Added comprehensive error handling for network issues and API errors
- ✅ Added `get_available_voices()` method with supported voices
**Supported Voices:**
- `diana` (Female) - **Default**
- `alex` (Male)
- `bella` (Female)
### 2. Database Migration (`main/manager-api/src/main/resources/db/changelog/202508141200.sql`)
**Changes:**
- ✅ Added 'diana' voice option to the `ai_tts_voice` table
- ✅ Updated default configuration to use 'diana' voice
- ✅ Changed default response format from 'wav' to 'mp3'
- ✅ Added speed and gain parameters to the configuration
### 3. Updated Master Changelog (`db.changelog-master.yaml`)
- ✅ Added the new migration to the changelog sequence
### 4. Test Script (`test_siliconflow_tts.py`)
- ✅ Created a test script to verify the implementation
- ✅ Tests voice generation with diana voice
- ✅ Validates configuration and error handling
## API Configuration
The updated SiliconFlow TTS provider now uses this configuration format:
```json
{
"type": "siliconflow",
"model": "FunAudioLLM/CosyVoice2-0.5B",
"voice": "diana",
"output_dir": "tmp/",
"access_token": "YOUR_TOKEN_HERE",
"response_format": "mp3",
"speed": 1.0,
"gain": 0
}
```
## Usage Example
The API request format matches exactly what you provided:
```python
import requests
url = "https://api.siliconflow.com/v1/audio/speech"
payload = {
"input": "Can you say it with a happy emotion? <|endofprompt|>I'm so happy, Spring Festival is coming!",
"response_format": "mp3",
"stream": False,
"speed": 1,
"gain": 0,
"model": "FunAudioLLM/CosyVoice2-0.5B"
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
```
## How to Test
1. **Set up your SiliconFlow API token** in the configuration
2. **Run the test script**: `python test_siliconflow_tts.py`
3. **Apply database migration** to add the diana voice option
4. **Configure the system** to use SiliconFlow TTS with diana voice
## Integration with Existing System
The SiliconFlow TTS provider is already registered in the system as `TTS_CosyVoiceSiliconflow`. After applying the database migration, users will be able to:
1. Select SiliconFlow CosyVoice as their TTS provider
2. Choose from available voices including the new 'diana' voice
3. Configure speed, gain, and response format
4. Use the improved error handling and logging
## Next Steps
1. Apply the database migration to add the diana voice
2. Update any existing configurations to use the new diana voice if desired
3. Test the integration with your SiliconFlow API token
4. The system will now default to using 'diana' voice for new SiliconFlow TTS configurations
The implementation maintains full compatibility with the existing system while adding the requested diana voice support and improving the API integration.

View file

@ -1,102 +0,0 @@
# ASR Troubleshooting Guide
## ✅ **FIXED: Whisper Model Parameters**
The issue was with incompatible parameters in the Sherpa-ONNX Whisper initialization. This has been fixed.
## 🔧 **What Was Fixed:**
### Before (Broken):
```python
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
encoder=self.encoder_path,
decoder=self.decoder_path,
tokens=self.tokens_path,
num_threads=2,
sample_rate=16000, # ❌ Not supported
feature_dim=80, # ❌ Not supported
decoding_method="greedy_search",
debug=False,
)
```
### After (Fixed):
```python
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
encoder=self.encoder_path,
decoder=self.decoder_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
```
## 🚀 **Your Server Should Now Work!**
The model files downloaded successfully:
- ✅ `tiny.en-encoder.onnx` (37.6MB)
- ✅ `tiny.en-decoder.onnx` (115MB)
- ✅ `tiny.en-tokens.txt` (836KB)
## 🎯 **Current Configuration:**
- **Model**: Whisper Tiny English
- **Size**: ~153MB total
- **Speed**: Very fast
- **Accuracy**: Good for English
- **Multi-client**: ✅ Supported
## 🧪 **Test Your Setup:**
Run the test script:
```bash
python test_whisper_model.py
```
## 🔄 **If You Still Have Issues:**
### Option 1: Try Different Model
Edit `main/xiaozhi-server/data/.config.yaml`:
```yaml
selected_module:
ASR: SherpaWhisperBaseEN # Larger, more stable
```
### Option 2: Use Original Multilingual
```yaml
selected_module:
ASR: SherpaASR # Fall back to working multilingual
```
## 📊 **Performance Expectations:**
### Whisper Tiny English:
- **Processing Time**: ~0.5-1.0 seconds per utterance
- **Memory Usage**: ~200MB
- **Concurrent Clients**: 5-10 kids simultaneously
- **Accuracy**: 85-90% for clear English speech
### Multiple Kids Scenario:
- **2-3 kids**: Excellent performance
- **4-6 kids**: Very good performance
- **7-10 kids**: Good performance
- **10+ kids**: May need hardware upgrade
## 🎉 **Success Indicators:**
When your server starts successfully, you'll see:
```
[core.utils.modules_initialize]-INFO-Initialize component: asr successful SherpaWhisperTinyEN
[core.websocket_server]-INFO-WebSocket server started on ws://0.0.0.0:8000
```
## 🎈 **Ready for Cheeko!**
Your kid companion bot is now configured with:
- ✅ Fast English-only ASR
- ✅ Multiple client support
- ✅ Optimized for children's voices
- ✅ Real-time processing
The kids can now talk to Cheeko simultaneously! 🎊

View file

@ -1,447 +0,0 @@
# VAD and ASR Filtering Implementation Plan
## Executive Summary
This document outlines a comprehensive plan to improve Voice Activity Detection (VAD) accuracy and reduce false positive transcriptions in the Xiaozhi ESP32 server system. The implementation focuses on reducing noise-triggered VAD events and filtering common false transcripts while preserving legitimate user input.
## Current Issues
1. **VAD False Triggers**
- Background noise triggering voice detection
- Environmental sounds (fans, rustling) causing false positives
- Too sensitive to non-speech audio
2. **ASR False Transcripts**
- Common false outputs: "yeah", "so", "thank you", "um", "uh"
- Short random words from noise
- Affecting response quality and user experience
## Implementation Plan
### Phase 1: VAD Optimization (Immediate)
#### 1.1 Configuration Updates
**File**: `main/xiaozhi-server/data/.config.yaml`
```yaml
VAD:
SileroVAD:
type: silero
threshold: 0.7 # Increased from 0.5
threshold_low: 0.4 # For hysteresis
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 1500 # Increased from 1000ms
frame_window_threshold: 5 # Increase from default 3
```
#### 1.2 Advanced VAD Configuration (Optional)
```yaml
VAD:
SileroVAD:
# ... existing config ...
# Advanced noise handling
noise_suppression:
enabled: true
pre_emphasis: 0.97 # High-pass filter coefficient
energy_threshold: 0.01 # Minimum energy level
spectral_subtraction: true # Remove stationary noise
```
### Phase 2: ASR Filtering System
#### 2.1 Context-Aware Filtering Module
**New File**: `main/xiaozhi-server/core/utils/asr_filter.py`
```python
from typing import Dict, List, Tuple, Optional
import re
from config.logger import setup_logging
logger = setup_logging()
class ASRFilter:
"""
Context-aware ASR filtering system to reduce false positives
while preserving legitimate user input
"""
def __init__(self, config: Dict):
self.config = config.get('ASR', {}).get('filtering', {})
self.enabled = self.config.get('enabled', True)
self.mode = self.config.get('mode', 'smart') # strict, smart, disabled
self.min_word_count = self.config.get('min_word_count', 2)
self.min_char_length = self.config.get('min_char_length', 3)
# Load filter lists
self.standalone_false_positives = self.config.get(
'standalone_false_positives',
["yeah", "so", "thanks", "okay", "um", "uh", "ah", "hmm", "oh"]
)
self.always_filter = self.config.get(
'always_filter',
["test test test", "one two three"]
)
# Context tracking
self.last_bot_utterance = ""
self.expecting_response = False
self.conversation_context = []
def should_filter(self, text: str, context: Optional[Dict] = None) -> Tuple[bool, str]:
"""
Determine if transcript should be filtered
Returns: (should_filter, reason)
"""
if not self.enabled or self.mode == 'disabled':
return False, "Filtering disabled"
# Clean and prepare text
original_text = text.strip()
cleaned_text = self._clean_text(text)
word_count = len(original_text.split())
# Always filter list
if any(pattern in cleaned_text for pattern in self.always_filter):
return True, "Matches always-filter pattern"
# Mode-specific filtering
if self.mode == 'strict':
return self._strict_filter(cleaned_text, word_count)
else: # smart mode
return self._smart_filter(cleaned_text, word_count, original_text, context)
def _clean_text(self, text: str) -> str:
"""Remove punctuation and normalize text"""
# Remove punctuation but keep spaces
cleaned = re.sub(r'[^\w\s]', '', text)
return cleaned.strip().lower()
def _strict_filter(self, text: str, word_count: int) -> Tuple[bool, str]:
"""Strict filtering mode"""
if len(text) < self.min_char_length:
return True, f"Too short ({len(text)} chars)"
if word_count < self.min_word_count:
return True, f"Too few words ({word_count})"
if text in self.standalone_false_positives:
return True, "Matches false positive list"
return False, "Passed strict filter"
def _smart_filter(self, text: str, word_count: int,
original: str, context: Optional[Dict]) -> Tuple[bool, str]:
"""Smart context-aware filtering"""
# Very short text
if len(text) < 2:
return True, "Single character or empty"
# Check if it's a response to a yes/no question
if context and context.get('expecting_response'):
if text in ['yes', 'no', 'yeah', 'nope', 'okay', 'sure']:
return False, "Valid response to question"
# Single word that's commonly a false positive
if word_count == 1 and text in self.standalone_false_positives:
# Check conversation context
if self._is_likely_noise(text, context):
return True, "Likely noise (single word, no context)"
# Multiple identical words (often noise)
words = text.split()
if len(set(words)) == 1 and len(words) > 2:
return True, "Repeated word pattern"
# Part of a longer phrase - usually legitimate
if word_count >= 3:
return False, "Part of longer phrase"
return False, "Passed smart filter"
def _is_likely_noise(self, text: str, context: Optional[Dict]) -> bool:
"""Determine if single word is likely noise based on context"""
if not context:
return True
# Check timing - if it comes immediately after bot stops speaking
time_since_bot = context.get('time_since_bot_utterance', float('inf'))
if time_since_bot < 0.5: # Within 500ms
return True
# Check if it matches recent pattern of noise
recent_filtered = context.get('recent_filtered', [])
if text in recent_filtered:
return True
return False
def update_context(self, key: str, value: any):
"""Update filtering context"""
if key == 'bot_utterance':
self.last_bot_utterance = value
self.expecting_response = self._is_question(value)
elif key == 'conversation':
self.conversation_context.append(value)
# Keep last 10 exchanges
self.conversation_context = self.conversation_context[-10:]
def _is_question(self, text: str) -> bool:
"""Check if bot utterance is a question"""
question_patterns = [
r'\?$', # Ends with ?
r'^(do|does|did|will|would|can|could|should|is|are|what|where|when|why|how)',
r'(right|correct|okay|yes or no)[\?\.]?$'
]
return any(re.search(pattern, text.lower()) for pattern in question_patterns)
```
#### 2.2 Configuration Schema
**Update**: `main/xiaozhi-server/data/.config.yaml`
```yaml
ASR:
# ... existing ASR config ...
filtering:
enabled: true
mode: "smart" # Options: "strict", "smart", "disabled"
# Basic thresholds
min_word_count: 2
min_char_length: 3
# Filter lists
standalone_false_positives:
- "yeah"
- "so"
- "thanks"
- "thank you"
- "okay"
- "ok"
- "um"
- "uh"
- "ah"
- "hmm"
- "oh"
- "well"
- "yes"
- "no"
always_filter:
- "test test test"
- "one two three"
- "testing testing"
- "hello hello hello"
# Smart mode settings
smart_mode:
consider_context: true
time_window_ms: 500 # Time after bot speaks to consider as noise
repetition_threshold: 3 # Filter if same word repeated this many times
```
### Phase 3: Integration Points
#### 3.1 Update ASR Base Class
**File**: `main/xiaozhi-server/core/providers/asr/base.py`
```python
# Add import
from core.utils.asr_filter import ASRFilter
# In __init__ method
self.asr_filter = ASRFilter(config) if config else None
# In handle_voice_stop method
async def handle_voice_stop(self, conn, asr_audio_task):
# ... existing code ...
# After getting transcript
if self.asr_filter and transcript:
should_filter, reason = self.asr_filter.should_filter(
transcript,
context={
'time_since_bot_utterance': time.time() - conn.last_bot_utterance_time,
'expecting_response': conn.expecting_user_response,
'recent_filtered': conn.recent_filtered_texts[-5:]
}
)
if should_filter:
logger.info(f"Filtered transcript: '{transcript}' - Reason: {reason}")
conn.recent_filtered_texts.append(transcript)
return
# Continue with normal processing
```
#### 3.2 Update Text Processing Utility
**File**: `main/xiaozhi-server/core/utils/util.py`
```python
def remove_punctuation_and_length(text, config=None, use_filter=True):
"""
Enhanced text processing with optional ASR filtering
"""
# ... existing punctuation removal code ...
if use_filter and config:
from core.utils.asr_filter import ASRFilter
asr_filter = ASRFilter(config)
should_filter, reason = asr_filter.should_filter(result)
if should_filter:
return 0, ""
return len(result), result
```
### Phase 4: Monitoring and Metrics
#### 4.1 Logging Enhancement
**File**: `main/xiaozhi-server/core/utils/asr_metrics.py`
```python
import json
from datetime import datetime
from collections import defaultdict
class ASRMetrics:
"""Track ASR filtering effectiveness"""
def __init__(self):
self.metrics = {
'total_transcripts': 0,
'filtered_count': 0,
'filter_reasons': defaultdict(int),
'filtered_words': defaultdict(int),
'false_positive_rate': 0.0
}
def record_transcript(self, text: str, filtered: bool, reason: str = None):
self.metrics['total_transcripts'] += 1
if filtered:
self.metrics['filtered_count'] += 1
if reason:
self.metrics['filter_reasons'][reason] += 1
self.metrics['filtered_words'][text.lower()] += 1
def calculate_stats(self):
total = self.metrics['total_transcripts']
if total > 0:
self.metrics['false_positive_rate'] = (
self.metrics['filtered_count'] / total * 100
)
def export_report(self, filepath: str):
self.calculate_stats()
report = {
'timestamp': datetime.now().isoformat(),
'metrics': self.metrics,
'top_filtered_words': dict(
sorted(self.metrics['filtered_words'].items(),
key=lambda x: x[1], reverse=True)[:10]
)
}
with open(filepath, 'w') as f:
json.dump(report, f, indent=2)
```
### Phase 5: Testing Strategy
#### 5.1 Unit Tests
**File**: `main/xiaozhi-server/tests/test_asr_filter.py`
```python
import pytest
from core.utils.asr_filter import ASRFilter
class TestASRFilter:
@pytest.fixture
def smart_filter(self):
config = {
'ASR': {
'filtering': {
'enabled': True,
'mode': 'smart',
'min_word_count': 2,
'min_char_length': 3
}
}
}
return ASRFilter(config)
def test_filter_single_false_positive(self, smart_filter):
should_filter, reason = smart_filter.should_filter("yeah")
assert should_filter == True
def test_keep_legitimate_phrase(self, smart_filter):
should_filter, reason = smart_filter.should_filter("Yeah, play some music")
assert should_filter == False
def test_filter_repeated_words(self, smart_filter):
should_filter, reason = smart_filter.should_filter("test test test")
assert should_filter == True
```
#### 5.2 Integration Tests
1. Test with recorded audio samples containing noise
2. Test with legitimate user commands
3. Measure false positive reduction rate
4. Ensure no legitimate commands are filtered
### Phase 6: Rollout Plan
#### 6.1 Gradual Deployment
1. **Week 1**: Deploy VAD configuration changes only
- Monitor for improvements in noise rejection
- Collect baseline metrics
2. **Week 2**: Enable ASR filtering in "smart" mode
- Monitor filtered transcripts
- Adjust filter lists based on data
3. **Week 3**: Fine-tune thresholds
- Analyze metrics reports
- Optimize for specific environment
#### 6.2 Rollback Strategy
1. Keep original configuration backed up
2. Feature flags for enabling/disabling filtering
3. Quick disable via config without code changes
### Performance Considerations
1. **Processing Overhead**
- Filtering adds < 1ms per transcript
- Negligible impact on response time
2. **Memory Usage**
- Context tracking uses < 1KB per connection
- Metrics collection uses < 100KB total
3. **CPU Impact**
- Regex operations are lightweight
- No heavy computations required
### Future Enhancements
1. **Machine Learning Integration**
- Train classifier on filtered vs. legitimate transcripts
- Adaptive threshold adjustment
2. **Multi-language Support**
- Extend filtering to other languages
- Language-specific false positive lists
3. **Advanced Noise Profiling**
- Learn environment-specific noise patterns
- Automatic VAD threshold adjustment
### Conclusion
This implementation plan provides a comprehensive approach to reducing VAD false triggers and ASR false positives while maintaining system responsiveness to legitimate user input. The phased approach allows for gradual deployment and optimization based on real-world usage data.

View file

@ -1,89 +0,0 @@
# SiliconFlow Voice Format Fix
## Issue
SiliconFlow CosyVoice API requires system-predefined voices to be prefixed with the model name in the format:
```
FunAudioLLM/CosyVoice2-0.5B:alex
```
## Solution Implemented
### 1. **Updated TTS Provider Logic**
The `siliconflow.py` provider now automatically handles voice formatting:
```python
# Voice configuration - default to diana with model prefix
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
voice_name = config.get("voice", "diana")
# If voice doesn't already contain model prefix, add it
if ":" not in voice_name:
self.voice = f"{self.model}:{voice_name}"
else:
self.voice = voice_name
```
### 2. **Voice Parameter in API Request**
The voice parameter is now properly included in the API payload:
```python
# Add voice parameter with model prefix (e.g., FunAudioLLM/CosyVoice2-0.5B:diana)
if self.voice:
payload["voice"] = self.voice
```
### 3. **Updated Available Voices**
The `get_available_voices()` method now returns properly formatted voice names:
```python
def get_available_voices(self):
model_prefix = self.model
return [
(f"{model_prefix}:diana", "Diana (Female)"),
(f"{model_prefix}:alex", "Alex (Male)"),
(f"{model_prefix}:bella", "Bella (Female)"),
]
```
## Configuration Examples
### Simple Configuration (Recommended)
```yaml
siliconflow:
model: FunAudioLLM/CosyVoice2-0.5B
voice: diana # Automatically becomes FunAudioLLM/CosyVoice2-0.5B:diana
```
### Full Format Configuration
```yaml
siliconflow:
model: FunAudioLLM/CosyVoice2-0.5B
voice: FunAudioLLM/CosyVoice2-0.5B:alex # Used as-is
```
## API Request Format
The final API request will look like:
```json
{
"input": "Hello world",
"response_format": "mp3",
"stream": true,
"speed": 1.0,
"gain": 0,
"model": "FunAudioLLM/CosyVoice2-0.5B",
"voice": "FunAudioLLM/CosyVoice2-0.5B:diana"
}
```
## Benefits
1. **User-Friendly**: Users can specify just the voice name (`diana`, `alex`, `bella`)
2. **Flexible**: Supports both simple names and full format
3. **Automatic**: Model prefix is added automatically
4. **Backward Compatible**: Existing full-format configurations still work
## Testing
Use `test_voice_format.py` to verify the voice formatting logic works correctly.
The system now properly handles the SiliconFlow voice format requirement while maintaining ease of use for configuration.

View file

@ -1,70 +0,0 @@
#!/usr/bin/env python3
"""
Check which ASR model is currently selected in the config
"""
import sys
import os
sys.path.append('main/xiaozhi-server')
from config.settings import load_config
def check_current_config():
"""Check the current ASR configuration"""
try:
print("🔍 Checking current configuration...")
# Load the config
config = load_config()
# Check selected ASR module
selected_asr = config.get("selected_module", {}).get("ASR", "Not found")
print(f"📋 Selected ASR module: {selected_asr}")
# Check if the ASR config exists
asr_configs = config.get("ASR", {})
if selected_asr in asr_configs:
asr_config = asr_configs[selected_asr]
print(f"✅ ASR configuration found:")
print(f" Type: {asr_config.get('type', 'Not specified')}")
print(f" Model Dir: {asr_config.get('model_dir', 'Not specified')}")
print(f" Model Type: {asr_config.get('model_type', 'Not specified')}")
print(f" Output Dir: {asr_config.get('output_dir', 'Not specified')}")
# Check if model files exist
model_dir = asr_config.get('model_dir', '')
if model_dir:
print(f"\n📁 Checking model directory: {model_dir}")
if os.path.exists(model_dir):
files = os.listdir(model_dir)
print(f" Files found: {len(files)}")
for f in files[:5]: # Show first 5 files
print(f" - {f}")
if len(files) > 5:
print(f" ... and {len(files) - 5} more files")
else:
print(" ❌ Model directory does not exist")
else:
print(f"❌ ASR configuration '{selected_asr}' not found!")
print(f"Available ASR configurations:")
for name in asr_configs.keys():
print(f" - {name}")
return True
except Exception as e:
print(f"❌ Error checking config: {e}")
return False
if __name__ == "__main__":
print("Configuration Checker")
print("=" * 30)
success = check_current_config()
if success:
print("\n✅ Configuration check completed!")
else:
print("\n❌ Configuration check failed!")
print("Make sure you're running this from the correct directory.")

View file

@ -1,89 +0,0 @@
#!/usr/bin/env python3
"""
Fix ASR configuration to use working Whisper Tiny English model
"""
import os
import yaml
def fix_asr_config():
"""Fix the ASR configuration to use a working model"""
config_file = "main/xiaozhi-server/data/.config.yaml"
print("🔧 Fixing ASR Configuration")
print("=" * 30)
try:
# Read current config
if not os.path.exists(config_file):
print(f"❌ Config file not found: {config_file}")
return False
with open(config_file, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
# Check current selection
current_asr = config.get("selected_module", {}).get("ASR", "Unknown")
print(f"📋 Current ASR: {current_asr}")
# Force to use Whisper Tiny (which we know works)
if "selected_module" not in config:
config["selected_module"] = {}
config["selected_module"]["ASR"] = "SherpaWhisperTinyEN"
# Ensure the Whisper Tiny config exists
if "ASR" not in config:
config["ASR"] = {}
config["ASR"]["SherpaWhisperTinyEN"] = {
"type": "sherpa_onnx_local",
"model_dir": "models/sherpa-onnx-whisper-tiny.en",
"model_type": "whisper",
"output_dir": "tmp/"
}
# Write back the config
with open(config_file, 'w', encoding='utf-8') as f:
yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
print("✅ Configuration updated!")
print("📋 New ASR: SherpaWhisperTinyEN")
print("🎯 Model: Whisper Tiny English (fast, reliable)")
# Check if model files exist
model_dir = "models/sherpa-onnx-whisper-tiny.en"
if os.path.exists(model_dir):
files = [f for f in os.listdir(model_dir) if f.endswith('.onnx') or f.endswith('.txt')]
print(f"📁 Model files found: {len(files)}")
for f in files:
print(f" ✓ {f}")
else:
print("📥 Model files will be downloaded automatically when server starts")
return True
except Exception as e:
print(f"❌ Error fixing config: {e}")
return False
if __name__ == "__main__":
print("ASR Configuration Fixer")
print("This will set your ASR to use Whisper Tiny English")
print()
success = fix_asr_config()
if success:
print("\n🎉 SUCCESS! Your ASR is now configured correctly!")
print("🚀 You can now start your server:")
print(" python app.py")
print("\n✅ Benefits of Whisper Tiny English:")
print(" - Fast processing")
print(" - English-only (no multilingual overhead)")
print(" - Perfect for multiple kids")
print(" - Reliable downloads from Hugging Face")
else:
print("\n❌ Failed to fix configuration.")
print("Please check the file permissions and try again.")

View file

@ -1,28 +0,0 @@
#!/usr/bin/env python3
"""
Install huggingface_hub for better model downloads
"""
import subprocess
import sys
def install_huggingface_hub():
"""Install huggingface_hub package"""
try:
print("Installing huggingface_hub...")
subprocess.check_call([
sys.executable, "-m", "pip", "install", "huggingface_hub"
])
print("✅ huggingface_hub installed successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install huggingface_hub: {e}")
return False
if __name__ == "__main__":
success = install_huggingface_hub()
if success:
print("\n🎉 You can now use Hugging Face models for better reliability!")
print("The system will automatically fallback to ModelScope if needed.")
else:
print("\n⚠️ Installation failed, but the system will still work with ModelScope.")

View file

@ -1,92 +0,0 @@
# Firmware Dictionary Setup Guide
## Adding Firmware Types to Dictionary Management
To properly display firmware information for your devices, you need to add the following dictionary entries in the web dashboard:
### Step 1: Access Dictionary Management
1. Login to your web dashboard
2. Navigate to **Dictionary Management** section
### Step 2: Find or Create FIRMWARE_TYPE Dictionary Type
1. Look for "FIRMWARE_TYPE" in the left panel
2. If it doesn't exist, click "Add Dictionary Type" and create:
- Dictionary Type Name: `Firmware Type`
- Dictionary Type Code: `FIRMWARE_TYPE`
### Step 3: Add Device Model Entries
Click on FIRMWARE_TYPE and add the following dictionary data entries:
#### Entry 1: DOIT AI Kit
- **Dictionary Label**: `DOIT AI-01 Kit`
- **Dictionary Value**: `doit-ai-01-kit`
- **Sort**: `1`
#### Entry 2: ESP32 Generic
- **Dictionary Label**: `ESP32 Generic`
- **Dictionary Value**: `esp32-generic`
- **Sort**: `2`
#### Entry 3: ESP32-S3 DevKit
- **Dictionary Label**: `ESP32-S3 DevKit`
- **Dictionary Value**: `esp32s3-devkit`
- **Sort**: `3`
#### Entry 4: XIAO ESP32S3
- **Dictionary Label**: `XIAO ESP32S3`
- **Dictionary Value**: `xiao-esp32s3`
- **Sort**: `4`
#### Entry 5: M5Stack Core
- **Dictionary Label**: `M5Stack Core`
- **Dictionary Value**: `m5stack-core`
- **Sort**: `5`
## Current Device Information from Logs
Your connected device is reporting:
- **Device Name**: doit-ai-01-kit
- **Firmware Version**: 1.7.6
- **Protocol Version**: 2024-11-05
- **MAC Address**: 68:25:DD:BB:4D:44
## Firmware Management Display
After adding these dictionary entries, the Firmware Management and Device Management pages will properly display:
- Device model names (instead of raw codes)
- Firmware versions
- Device capabilities
## Verification Steps
1. After adding dictionary entries, go to **Device Management**
2. You should see "DOIT AI-01 Kit" instead of "doit-ai-01-kit"
3. The firmware version "1.7.6" should be displayed in the table
4. In **Firmware Management**, you can now add OTA updates for these device types
## Backend Integration
The system is already configured to:
1. Log firmware details when devices connect via MCP protocol
2. Store firmware version in the database (appVersion field)
3. Display firmware info in Device Management table
The enhanced logging shows:
```
============================================================
DEVICE CONNECTED - Firmware Details:
Device Name: doit-ai-01-kit
Firmware Version: 1.7.6
Protocol Version: 2024-11-05
Device ID: 68_25_dd_bb_4d_44
MAC Address: 68:25:DD:BB:4D:44
Capabilities: ['tools']
============================================================
```
## Next Steps
1. Add the dictionary entries as described above
2. Verify device display in Device Management
3. Upload firmware files in Firmware Management for OTA updates
4. Configure auto-update settings per device if needed

View file

@ -1,169 +0,0 @@
#!/usr/bin/env python3
"""
Setup script for English-only ASR configuration
Automatically configures the best English ASR model for your use case
"""
import os
import yaml
import sys
def setup_english_asr():
"""Setup English-only ASR configuration"""
print("🎯 English-Only ASR Setup")
print("=" * 40)
print()
# Check if config file exists
config_file = "main/xiaozhi-server/data/.config.yaml"
main_config = "main/xiaozhi-server/config.yaml"
if not os.path.exists("main/xiaozhi-server"):
print("❌ Please run this script from the project root directory")
return False
# Create data directory if it doesn't exist
os.makedirs("main/xiaozhi-server/data", exist_ok=True)
print("🤖 What type of application are you building?")
print("1. 👶 Kids companion bot (RECOMMENDED: Gigaspeech)")
print("2. ⚡ Fast response bot (Whisper Tiny)")
print("3. 🎯 General English bot (Whisper Base)")
print("4. 🏆 Highest accuracy (Whisper Small)")
print()
while True:
try:
choice = input("Enter your choice (1-4): ").strip()
if choice in ['1', '2', '3', '4']:
break
print("Please enter 1, 2, 3, or 4")
except KeyboardInterrupt:
print("\n👋 Setup cancelled")
return False
# Model configurations
models = {
'1': {
'name': 'SherpaZipformerGigaspeechEN',
'description': 'Gigaspeech English (Best for Kids)',
'benefits': ['Massive vocabulary', 'Perfect for creative language', 'YouTube training data', 'Multiple client support']
},
'2': {
'name': 'SherpaWhisperTinyEN',
'description': 'Whisper Tiny English (Fastest)',
'benefits': ['Fastest processing', 'Small size (153MB)', 'Quick responses', 'Good for simple conversations']
},
'3': {
'name': 'SherpaWhisperBaseEN',
'description': 'Whisper Base English (Balanced)',
'benefits': ['Good balance of speed/accuracy', 'Moderate size (74MB)', 'Reliable performance', 'General purpose']
},
'4': {
'name': 'SherpaWhisperSmallEN',
'description': 'Whisper Small English (Highest Accuracy)',
'benefits': ['Best accuracy', 'Large size (244MB)', 'Excellent for complex speech', 'Professional use']
}
}
selected_model = models[choice]
print(f"\n✅ Selected: {selected_model['description']}")
print("📋 Benefits:")
for benefit in selected_model['benefits']:
print(f" • {benefit}")
print()
try:
# Create or update config
config = {}
# Load existing config if it exists
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f) or {}
# Set up the configuration
if 'selected_module' not in config:
config['selected_module'] = {}
config['selected_module']['ASR'] = selected_model['name']
# Ensure ASR configurations exist
if 'ASR' not in config:
config['ASR'] = {}
# Add all English ASR configurations
english_models = {
'SherpaZipformerGigaspeechEN': {
'type': 'sherpa_onnx_local',
'model_dir': 'models/sherpa-onnx-zipformer-gigaspeech-2023-12-12',
'model_type': 'zipformer',
'output_dir': 'tmp/'
},
'SherpaWhisperTinyEN': {
'type': 'sherpa_onnx_local',
'model_dir': 'models/sherpa-onnx-whisper-tiny.en',
'model_type': 'whisper',
'output_dir': 'tmp/'
},
'SherpaWhisperBaseEN': {
'type': 'sherpa_onnx_local',
'model_dir': 'models/sherpa-onnx-whisper-base.en',
'model_type': 'whisper',
'output_dir': 'tmp/'
},
'SherpaWhisperSmallEN': {
'type': 'sherpa_onnx_local',
'model_dir': 'models/sherpa-onnx-whisper-small.en',
'model_type': 'whisper',
'output_dir': 'tmp/'
}
}
config['ASR'].update(english_models)
# Write the config
with open(config_file, 'w', encoding='utf-8') as f:
yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
print("✅ Configuration updated successfully!")
print(f"📁 Config file: {config_file}")
print(f"🎯 Selected ASR: {selected_model['name']}")
print()
# Special instructions for Gigaspeech
if choice == '1':
print("🔽 Gigaspeech Model Setup:")
print("The Gigaspeech model will be downloaded automatically when you start the server.")
print("If automatic download fails, you can run:")
print(" python download_gigaspeech_manual.py")
print()
print("🚀 Next Steps:")
print("1. Start your server: python main/xiaozhi-server/app.py")
print("2. The English model will download automatically")
print("3. Enjoy 3x faster English processing!")
print()
print("🎉 English-only ASR setup complete!")
return True
except Exception as e:
print(f"❌ Error setting up configuration: {e}")
return False
if __name__ == "__main__":
print("English-Only ASR Setup Script")
print("Configures the best English ASR model for your needs")
print()
success = setup_english_asr()
if success:
print("\n🎯 SUCCESS! Your English ASR is ready!")
print("Your bot will now process English speech much faster and more accurately.")
else:
print("\n❌ Setup failed. Please check the error messages above.")
sys.exit(1)