mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'Production1' into flutter-con
This commit is contained in:
commit
624b2020d6
154 changed files with 9027 additions and 344 deletions
452
FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md
Normal file
452
FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
# Firmware Update System Documentation
|
||||
|
||||
## Table of Contents
|
||||
1. [Overview](#overview)
|
||||
2. [Architecture](#architecture)
|
||||
3. [Components](#components)
|
||||
4. [Firmware Upload Process](#firmware-upload-process)
|
||||
5. [OTA Update Flow](#ota-update-flow)
|
||||
6. [API Endpoints](#api-endpoints)
|
||||
7. [Database Schema](#database-schema)
|
||||
8. [Configuration](#configuration)
|
||||
9. [Security Features](#security-features)
|
||||
10. [Device-Server Communication](#device-server-communication)
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Xiaozhi ESP32 Server implements a comprehensive Over-The-Air (OTA) firmware update system that allows remote firmware updates for ESP32 devices. The system supports automatic version checking, secure firmware distribution, and device-specific update policies.
|
||||
|
||||
### Key Features
|
||||
- Automatic version comparison and update detection
|
||||
- Secure firmware storage with MD5 hash verification
|
||||
- Per-device update control (auto-update enable/disable)
|
||||
- Download attempt limiting (3 attempts per UUID)
|
||||
- Support for multiple firmware types (.bin and .apk)
|
||||
- RESTful API for firmware management
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌──────────────────┐ ┌────────────────┐
|
||||
│ ESP32 Device │────▶│ Manager API │────▶│ Firmware Store │
|
||||
│ │◀────│ (Java Spring) │◀────│ (uploadfile/) │
|
||||
└─────────────────┘ └──────────────────┘ └────────────────┘
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────┐ │
|
||||
│ │ Database │ │
|
||||
│ │ (ai_ota) │ │
|
||||
│ └──────────────────┘ │
|
||||
│ │
|
||||
▼ │
|
||||
┌─────────────────┐ │
|
||||
│ Xiaozhi Server │ │
|
||||
│ (Python) │◀──────────────────────────────────────┘
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Manager API (Java Spring Boot)
|
||||
- **Location**: `main/manager-api/`
|
||||
- **Main Controllers**:
|
||||
- `OTAController.java`: Handles device OTA check requests
|
||||
- `OTAMagController.java`: Manages firmware upload/download
|
||||
- **Services**:
|
||||
- `OtaServiceImpl.java`: Business logic for OTA operations
|
||||
- `DeviceServiceImpl.java`: Device management and update checks
|
||||
|
||||
### 2. Xiaozhi Server (Python)
|
||||
- **Location**: `main/xiaozhi-server/`
|
||||
- **OTA Handler**: `core/api/ota_handler.py`
|
||||
- Provides fallback OTA endpoint for direct device connections
|
||||
|
||||
### 3. Firmware Storage
|
||||
- **Location**: `main/manager-api/uploadfile/`
|
||||
- Files stored with MD5 hash as filename
|
||||
- Supported formats: `.bin`, `.apk`
|
||||
|
||||
---
|
||||
|
||||
## Firmware Upload Process
|
||||
|
||||
### Step 1: Admin Upload
|
||||
```http
|
||||
POST /otaMag/upload
|
||||
Content-Type: multipart/form-data
|
||||
```
|
||||
|
||||
**Process Flow**:
|
||||
1. Admin uploads firmware file through web interface
|
||||
2. System validates file extension (.bin or .apk only)
|
||||
3. MD5 hash calculated for the file
|
||||
4. File saved as: `uploadfile/{md5_hash}.{extension}`
|
||||
5. If file already exists (same MD5), returns existing path
|
||||
6. Path returned to admin for database entry
|
||||
|
||||
**Code Location**: `OTAMagController.java:231-279`
|
||||
|
||||
### Step 2: Database Registration
|
||||
Admin creates OTA entry with:
|
||||
- **Firmware Name**: Descriptive name
|
||||
- **Type**: Device type (e.g., "esp32-generic", "doit-ai-01-kit")
|
||||
- **Version**: Semantic version (e.g., "1.7.6")
|
||||
- **File Path**: Path from upload step
|
||||
- **Size**: File size in bytes
|
||||
- **Remark**: Optional description
|
||||
|
||||
---
|
||||
|
||||
## OTA Update Flow
|
||||
|
||||
### 1. Device Check Request
|
||||
```http
|
||||
POST /ota/
|
||||
Headers:
|
||||
Device-Id: {MAC_ADDRESS}
|
||||
Client-Id: {CLIENT_ID}
|
||||
Body:
|
||||
{
|
||||
"application": {
|
||||
"version": "1.7.6"
|
||||
},
|
||||
"board": {
|
||||
"type": "esp32-generic"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Server Processing
|
||||
**Location**: `DeviceServiceImpl.java - checkDeviceActive()`
|
||||
|
||||
1. **Device Validation**:
|
||||
- Verify MAC address format
|
||||
- Check if device is registered in database
|
||||
|
||||
2. **Update Decision Logic**:
|
||||
```java
|
||||
if (device == null) {
|
||||
// Device not registered - no update
|
||||
return current_firmware_info;
|
||||
}
|
||||
|
||||
if (device.autoUpdate != 0) {
|
||||
// Check for newer version
|
||||
OtaEntity latest = getLatestOta(device.type);
|
||||
if (compareVersions(latest.version, current.version) > 0) {
|
||||
// Generate download URL
|
||||
return firmware_with_download_url;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Download URL Generation**:
|
||||
- Create temporary UUID
|
||||
- Store OTA ID in Redis: `ota:id:{uuid}`
|
||||
- Generate URL: `/otaMag/download/{uuid}`
|
||||
- URL valid for 3 download attempts
|
||||
|
||||
### 3. Server Response
|
||||
```json
|
||||
{
|
||||
"server_time": {
|
||||
"timestamp": 1703123456789,
|
||||
"timezone_offset": 480
|
||||
},
|
||||
"firmware": {
|
||||
"version": "1.7.7",
|
||||
"url": "http://server:8002/otaMag/download/abc-123-def"
|
||||
},
|
||||
"websocket": {
|
||||
"url": "ws://server:8000/xiaozhi/v1/"
|
||||
},
|
||||
"mqtt": {
|
||||
"endpoint": "broker:1883",
|
||||
"client_id": "GID_test@@@mac@@@uuid",
|
||||
"username": "base64_encoded_data",
|
||||
"password": "hmac_signature"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Firmware Download
|
||||
**Endpoint**: `GET /otaMag/download/{uuid}`
|
||||
|
||||
**Process**:
|
||||
1. Validate UUID exists in Redis
|
||||
2. Check download count (max 3 attempts)
|
||||
3. Retrieve firmware file from storage
|
||||
4. Return file as binary stream
|
||||
5. Increment download counter
|
||||
6. Clean up after 3 downloads
|
||||
|
||||
**Security Features**:
|
||||
- UUID expires after use
|
||||
- Download attempt limiting
|
||||
- File path validation
|
||||
- Safe filename generation
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### OTA Check Endpoints
|
||||
|
||||
#### POST /ota/
|
||||
- **Purpose**: Device firmware update check
|
||||
- **Headers**: Device-Id, Client-Id
|
||||
- **Response**: Update information if available
|
||||
|
||||
#### POST /ota/activate
|
||||
- **Purpose**: Quick device activation check
|
||||
- **Headers**: Device-Id, Client-Id
|
||||
- **Response**: 200 if registered, 202 if not
|
||||
|
||||
### Management Endpoints
|
||||
|
||||
#### GET /otaMag
|
||||
- **Purpose**: List all firmware entries
|
||||
- **Permission**: superAdmin
|
||||
- **Parameters**: page, limit
|
||||
|
||||
#### POST /otaMag
|
||||
- **Purpose**: Create firmware entry
|
||||
- **Permission**: superAdmin
|
||||
- **Body**: OtaEntity
|
||||
|
||||
#### PUT /otaMag/{id}
|
||||
- **Purpose**: Update firmware entry
|
||||
- **Permission**: superAdmin
|
||||
|
||||
#### DELETE /otaMag/{id}
|
||||
- **Purpose**: Delete firmware entry
|
||||
- **Permission**: superAdmin
|
||||
|
||||
#### POST /otaMag/upload
|
||||
- **Purpose**: Upload firmware file
|
||||
- **Permission**: superAdmin
|
||||
- **Returns**: File path for database
|
||||
|
||||
#### GET /otaMag/download/{uuid}
|
||||
- **Purpose**: Download firmware file
|
||||
- **Public**: Yes (with valid UUID)
|
||||
- **Limit**: 3 attempts per UUID
|
||||
|
||||
---
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Table: `ai_ota`
|
||||
```sql
|
||||
CREATE TABLE ai_ota (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
firmware_name VARCHAR(255),
|
||||
type VARCHAR(100), -- Device type
|
||||
version VARCHAR(50), -- Semantic version
|
||||
size BIGINT, -- File size in bytes
|
||||
remark TEXT, -- Description
|
||||
firmware_path VARCHAR(500), -- File storage path
|
||||
sort INT, -- Display order
|
||||
updater BIGINT,
|
||||
update_date DATETIME,
|
||||
creator BIGINT,
|
||||
create_date DATETIME
|
||||
);
|
||||
```
|
||||
|
||||
### Table: `ai_device`
|
||||
```sql
|
||||
CREATE TABLE ai_device (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
mac_address VARCHAR(50),
|
||||
app_version VARCHAR(50), -- Current firmware version
|
||||
auto_update TINYINT, -- 0=disabled, 1=enabled
|
||||
-- other fields...
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### System Parameters
|
||||
Configure in `sys_params` table or through Parameter Management UI:
|
||||
|
||||
1. **server.websocket**
|
||||
- WebSocket server URL for device connections
|
||||
- Example: `ws://server:8000/xiaozhi/v1/`
|
||||
|
||||
2. **server.ota**
|
||||
- OTA server base URL
|
||||
- Example: `http://server:8002/xiaozhi/`
|
||||
|
||||
### Device Types
|
||||
Configure in Dictionary Management (FIRMWARE_TYPE):
|
||||
- `doit-ai-01-kit`: DOIT AI-01 Kit
|
||||
- `esp32-generic`: ESP32 Generic
|
||||
- `esp32s3-devkit`: ESP32-S3 DevKit
|
||||
- `xiao-esp32s3`: XIAO ESP32S3
|
||||
- `m5stack-core`: M5Stack Core
|
||||
|
||||
---
|
||||
|
||||
## Security Features
|
||||
|
||||
### 1. File Upload Security
|
||||
- Extension validation (.bin, .apk only)
|
||||
- MD5 hash verification
|
||||
- Duplicate detection
|
||||
- Admin permission required
|
||||
|
||||
### 2. Download Security
|
||||
- Temporary UUID generation
|
||||
- Redis-based token management
|
||||
- Download attempt limiting (3 max)
|
||||
- Automatic cleanup after use
|
||||
|
||||
### 3. Version Control
|
||||
- Semantic versioning comparison
|
||||
- Per-device update control
|
||||
- Type-specific firmware matching
|
||||
|
||||
### 4. MQTT Authentication
|
||||
- HMAC-SHA256 signature generation
|
||||
- Base64 encoded credentials
|
||||
- Session-specific UUIDs
|
||||
|
||||
---
|
||||
|
||||
## Device-Server Communication
|
||||
|
||||
### 1. Initial Connection
|
||||
Device connects to OTA endpoint with:
|
||||
- MAC address as Device-Id
|
||||
- Current firmware version
|
||||
- Board type information
|
||||
|
||||
### 2. Update Check Flow
|
||||
```
|
||||
Device Manager API Database
|
||||
│ │ │
|
||||
├──POST /ota/──────────────▶│ │
|
||||
│ (version, type) │ │
|
||||
│ ├──Check Device────────▶│
|
||||
│ │◀─────────────────────┤
|
||||
│ │ │
|
||||
│ ├──Get Latest OTA──────▶│
|
||||
│ │◀─────────────────────┤
|
||||
│ │ │
|
||||
│◀──Response────────────────┤ │
|
||||
│ (download URL if update) │ │
|
||||
│ │ │
|
||||
├──GET /download/{uuid}────▶│ │
|
||||
│ │ │
|
||||
│◀──Firmware Binary─────────┤ │
|
||||
```
|
||||
|
||||
### 3. Fallback Support
|
||||
If Manager API unavailable, devices can connect to:
|
||||
- Xiaozhi Server OTA endpoint: `http://server:8003/ota/`
|
||||
- Provides basic connectivity information
|
||||
- No firmware updates (returns current version)
|
||||
|
||||
---
|
||||
|
||||
## Version Comparison Logic
|
||||
|
||||
The system uses semantic versioning (MAJOR.MINOR.PATCH):
|
||||
|
||||
```java
|
||||
private int compareVersions(String v1, String v2) {
|
||||
String[] parts1 = v1.split("\\.");
|
||||
String[] parts2 = v2.split("\\.");
|
||||
|
||||
for (int i = 0; i < Math.max(parts1.length, parts2.length); i++) {
|
||||
int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
|
||||
int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
|
||||
|
||||
if (num1 != num2) {
|
||||
return Integer.compare(num1, num2);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
**Examples**:
|
||||
- 1.7.7 > 1.7.6 ✓ (Update available)
|
||||
- 2.0.0 > 1.9.9 ✓ (Major update)
|
||||
- 1.7.6 = 1.7.6 ✗ (No update)
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **"OTA接口不正常,缺少websocket地址"**
|
||||
- Solution: Configure `server.websocket` parameter
|
||||
|
||||
2. **"OTA接口不正常,缺少ota地址"**
|
||||
- Solution: Configure `server.ota` parameter
|
||||
|
||||
3. **Firmware file not found**
|
||||
- Check file exists in `uploadfile/` directory
|
||||
- Verify path in database matches actual file
|
||||
|
||||
4. **Device not receiving updates**
|
||||
- Check `auto_update` flag is enabled (not 0)
|
||||
- Verify device type matches firmware type
|
||||
- Ensure version number is higher
|
||||
|
||||
5. **Download limit exceeded**
|
||||
- UUID expired after 3 attempts
|
||||
- Generate new download link
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Version Management**
|
||||
- Use semantic versioning consistently
|
||||
- Test firmware thoroughly before deployment
|
||||
- Keep previous versions for rollback
|
||||
|
||||
2. **Security**
|
||||
- Regular security audits of firmware
|
||||
- Monitor download patterns for abuse
|
||||
- Use HTTPS in production
|
||||
|
||||
3. **Device Management**
|
||||
- Group devices by type for targeted updates
|
||||
- Implement staged rollouts for critical updates
|
||||
- Monitor update success rates
|
||||
|
||||
4. **Storage Management**
|
||||
- Regular cleanup of old firmware files
|
||||
- Backup firmware files externally
|
||||
- Monitor disk space usage
|
||||
|
||||
---
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements to consider:
|
||||
- Delta updates for bandwidth optimization
|
||||
- Rollback mechanism for failed updates
|
||||
- Update scheduling and staging
|
||||
- Device group management
|
||||
- Update progress tracking
|
||||
- Firmware signing and verification
|
||||
- Automated testing before deployment
|
||||
|
||||
---
|
||||
|
||||
*Last Updated: 2025-08-25*
|
||||
*Document Version: 1.0.0*
|
||||
221
MANAGER_API_DOCUMENTATION.md
Normal file
221
MANAGER_API_DOCUMENTATION.md
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
# Manager API Documentation Guide
|
||||
|
||||
## Swagger/OpenAPI Documentation
|
||||
|
||||
The Manager API includes built-in Swagger/OpenAPI documentation using SpringDoc OpenAPI v2.8.8.
|
||||
|
||||
### Accessing Swagger UI
|
||||
|
||||
Once the Manager API is running, you can access the interactive API documentation at:
|
||||
|
||||
```
|
||||
http://localhost:8080/swagger-ui/index.html
|
||||
```
|
||||
|
||||
Replace `localhost:8080` with your actual server address and port.
|
||||
|
||||
### API Groups
|
||||
|
||||
The API is organized into the following groups:
|
||||
|
||||
1. **Device APIs** (`/device/**`)
|
||||
- Device registration
|
||||
- Device management
|
||||
- Device binding/unbinding
|
||||
- Device status reporting
|
||||
|
||||
2. **Agent APIs** (`/agent/**`)
|
||||
- Agent management
|
||||
- Agent configuration
|
||||
- Agent templates
|
||||
- Chat history
|
||||
- Memory management
|
||||
- Voice print management
|
||||
- MCP access points
|
||||
|
||||
3. **Model APIs** (`/models/**`)
|
||||
- Model configuration
|
||||
- Model providers
|
||||
- Voice models
|
||||
- LLM models
|
||||
- TTS/ASR/VAD models
|
||||
|
||||
4. **OTA APIs** (`/ota/**`)
|
||||
- Over-the-air updates
|
||||
- Firmware management
|
||||
- Update status
|
||||
|
||||
5. **Timbre APIs** (`/ttsVoice/**`)
|
||||
- TTS voice management
|
||||
- Voice configuration
|
||||
|
||||
6. **Admin APIs** (`/admin/**`)
|
||||
- User management
|
||||
- System administration
|
||||
- Server management
|
||||
|
||||
7. **User APIs** (`/user/**`)
|
||||
- User authentication
|
||||
- User profile
|
||||
- Password management
|
||||
|
||||
8. **Config APIs** (`/config/**`)
|
||||
- System configuration
|
||||
- Agent model configuration
|
||||
|
||||
### OpenAPI JSON Specification
|
||||
|
||||
You can access the raw OpenAPI specification at:
|
||||
|
||||
```
|
||||
http://localhost:8080/v3/api-docs
|
||||
```
|
||||
|
||||
For specific API groups:
|
||||
```
|
||||
http://localhost:8080/v3/api-docs/device
|
||||
http://localhost:8080/v3/api-docs/agent
|
||||
http://localhost:8080/v3/api-docs/models
|
||||
http://localhost:8080/v3/api-docs/ota
|
||||
http://localhost:8080/v3/api-docs/timbre
|
||||
http://localhost:8080/v3/api-docs/admin
|
||||
http://localhost:8080/v3/api-docs/user
|
||||
http://localhost:8080/v3/api-docs/config
|
||||
```
|
||||
|
||||
## Key API Endpoints
|
||||
|
||||
### Authentication
|
||||
- `POST /login` - User login
|
||||
- `POST /logout` - User logout
|
||||
- `POST /user/register` - User registration
|
||||
|
||||
### Agent Management
|
||||
- `GET /agent/list` - Get user's agents
|
||||
- `GET /agent/{id}` - Get agent details
|
||||
- `POST /agent` - Create new agent
|
||||
- `PUT /agent/{id}` - Update agent
|
||||
- `DELETE /agent/{id}` - Delete agent
|
||||
- `PUT /agent/saveMemory/{macAddress}` - Update agent memory
|
||||
|
||||
### Device Management
|
||||
- `POST /device/register` - Register device
|
||||
- `POST /device/bind` - Bind device to user
|
||||
- `POST /device/unbind` - Unbind device
|
||||
- `GET /device/list` - Get user's devices
|
||||
- `POST /device/report` - Device status report
|
||||
|
||||
### Model Configuration
|
||||
- `GET /models/provider` - Get model providers
|
||||
- `POST /models/provider` - Add model provider
|
||||
- `PUT /models/provider/{id}` - Update model provider
|
||||
- `DELETE /models/provider/{id}` - Delete model provider
|
||||
- `GET /models/config` - Get model configurations
|
||||
- `GET /models/voice/{modelId}` - Get voice options for TTS model
|
||||
|
||||
### Configuration
|
||||
- `GET /config/agentModels` - Get agent model configuration
|
||||
- `POST /config/agentModels` - Update agent model configuration
|
||||
|
||||
## API Authentication
|
||||
|
||||
Most API endpoints require authentication. The API uses Shiro for security:
|
||||
|
||||
1. **Login** to get a session token:
|
||||
```bash
|
||||
POST /login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "your-username",
|
||||
"password": "your-password"
|
||||
}
|
||||
```
|
||||
|
||||
2. **Use the token** in subsequent requests (stored in cookies/session)
|
||||
|
||||
3. **Permissions** are role-based:
|
||||
- `sys:role:normal` - Normal user permissions
|
||||
- `sys:role:superAdmin` - Administrator permissions
|
||||
|
||||
## Example API Calls
|
||||
|
||||
### Create Memory Provider
|
||||
```bash
|
||||
POST /models/provider
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"modelType": "Memory",
|
||||
"providerCode": "mem0ai",
|
||||
"name": "Mem0 Memory Provider",
|
||||
"fields": [
|
||||
{
|
||||
"key": "api_key",
|
||||
"label": "API Key",
|
||||
"type": "password",
|
||||
"value": "your-mem0-api-key"
|
||||
}
|
||||
],
|
||||
"sort": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Update Agent Memory
|
||||
```bash
|
||||
PUT /agent/saveMemory/{macAddress}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"summaryMemory": "Memory configuration instructions"
|
||||
}
|
||||
```
|
||||
|
||||
### Get Agent Configuration
|
||||
```bash
|
||||
GET /agent/{agentId}
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
The API uses DTOs (Data Transfer Objects) for request/response:
|
||||
|
||||
- **AgentDTO** - Agent information
|
||||
- **AgentMemoryDTO** - Agent memory update
|
||||
- **DeviceDTO** - Device information
|
||||
- **ModelConfigDTO** - Model configuration
|
||||
- **ModelProviderDTO** - Model provider configuration
|
||||
|
||||
All DTOs include Swagger annotations for documentation.
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API returns standardized error responses:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0, // 0 for success, non-zero for errors
|
||||
"msg": "Success or error message",
|
||||
"data": {} // Response data
|
||||
}
|
||||
```
|
||||
|
||||
Common error codes:
|
||||
- `401` - Unauthorized
|
||||
- `403` - Forbidden
|
||||
- `404` - Not found
|
||||
- `500` - Internal server error
|
||||
|
||||
## Development Tips
|
||||
|
||||
1. **Use Swagger UI** for testing APIs directly in the browser
|
||||
2. **Check annotations** in controller classes for detailed API documentation
|
||||
3. **Review DTOs** for request/response structures
|
||||
4. **Monitor logs** for debugging API issues
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- Controller classes in: `src/main/java/xiaozhi/modules/*/controller/`
|
||||
- DTO classes in: `src/main/java/xiaozhi/modules/*/dto/`
|
||||
- Entity classes in: `src/main/java/xiaozhi/modules/*/entity/`
|
||||
- Service implementations in: `src/main/java/xiaozhi/modules/*/service/`
|
||||
330
MEM0_INTEGRATION_GUIDE.md
Normal file
330
MEM0_INTEGRATION_GUIDE.md
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
# Mem0 Integration Guide for Xiaozhi ESP32 Server
|
||||
|
||||
## Overview
|
||||
Mem0 is a memory management system integrated into the Xiaozhi ESP32 server that provides persistent memory capabilities for AI agents. This guide explains how to configure and use mem0 with both the manager API and web dashboard.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
1. **Memory Provider** (`main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py`)
|
||||
- Handles memory storage and retrieval
|
||||
- Integrates with Mem0 cloud service
|
||||
- Provides search and query capabilities
|
||||
|
||||
2. **Manager API** (`main/manager-api`)
|
||||
- REST endpoints for memory configuration
|
||||
- Agent memory management
|
||||
- Database persistence
|
||||
|
||||
3. **Web Dashboard** (`main/manager-web`)
|
||||
- UI for configuring memory providers
|
||||
- Agent memory settings
|
||||
- Visual management interface
|
||||
|
||||
## Configuration
|
||||
|
||||
### 1. Setting Up Mem0 API Key
|
||||
|
||||
#### Via Web Dashboard:
|
||||
1. Navigate to **Provider Management** page
|
||||
2. Click **Add** button
|
||||
3. Select **Memory Module** as Category
|
||||
4. Choose **mem0ai** as Provider Code
|
||||
5. Enter configuration:
|
||||
```json
|
||||
{
|
||||
"api_key": "your-mem0-api-key",
|
||||
"api_version": "v1.1"
|
||||
}
|
||||
```
|
||||
6. Save the provider configuration
|
||||
|
||||
#### Via Manager API:
|
||||
```bash
|
||||
POST /api/model/provider
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"modelType": "Memory",
|
||||
"providerCode": "mem0ai",
|
||||
"name": "Mem0 Memory Provider",
|
||||
"fields": [
|
||||
{
|
||||
"key": "api_key",
|
||||
"label": "API Key",
|
||||
"type": "password",
|
||||
"value": "your-mem0-api-key"
|
||||
},
|
||||
{
|
||||
"key": "api_version",
|
||||
"label": "API Version",
|
||||
"type": "text",
|
||||
"value": "v1.1"
|
||||
}
|
||||
],
|
||||
"sort": 1
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Configuring Agent Memory
|
||||
|
||||
#### Via Web Dashboard:
|
||||
1. Go to **Agent Management**
|
||||
2. Create or edit an agent
|
||||
3. In the agent configuration, enable memory:
|
||||
- Toggle **Enable Memory** option
|
||||
- Select **mem0ai** as memory provider
|
||||
- Configure summary memory prompt
|
||||
|
||||
#### Via Manager API:
|
||||
```bash
|
||||
POST /api/agent
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "My AI Assistant",
|
||||
"summaryMemory": "Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories within limited space. Summarize important user information from conversations to provide more personalized service in future interactions.",
|
||||
"memoryProvider": "mem0ai",
|
||||
"enableMemory": true
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Updating Agent Memory
|
||||
|
||||
The system supports dynamic memory updates through the API:
|
||||
|
||||
```bash
|
||||
PUT /api/agent/saveMemory/{macAddress}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"summaryMemory": "Updated memory instructions for the agent"
|
||||
}
|
||||
```
|
||||
|
||||
## Memory Flow
|
||||
|
||||
### 1. Memory Save Process
|
||||
```python
|
||||
# When a conversation occurs:
|
||||
1. Messages are collected from the dialogue
|
||||
2. System filters out system messages
|
||||
3. Formatted messages are sent to Mem0 API
|
||||
4. Memory is associated with the agent's role_id
|
||||
5. Result is logged for debugging
|
||||
```
|
||||
|
||||
### 2. Memory Query Process
|
||||
```python
|
||||
# When agent needs to recall information:
|
||||
1. Query string is sent to search method
|
||||
2. Mem0 searches memories for the user_id (role_id)
|
||||
3. Results are formatted with timestamps
|
||||
4. Memories are sorted by recency (newest first)
|
||||
5. Formatted memory string is returned to agent
|
||||
```
|
||||
|
||||
## Integration Points
|
||||
|
||||
### WebSocket Server Integration
|
||||
The memory provider is initialized in `websocket_server.py`:
|
||||
- Checks if "Memory" is in selected_modules
|
||||
- Creates memory provider instance
|
||||
- Passes to ConnectionHandler for use during conversations
|
||||
|
||||
### Connection Handler
|
||||
In `connection.py`, the memory provider:
|
||||
- Saves conversation memories after each interaction
|
||||
- Queries memories when needed for context
|
||||
- Integrates with the dialogue flow
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Provider Management
|
||||
- `GET /api/model/provider` - List all providers including memory
|
||||
- `POST /api/model/provider` - Add new memory provider
|
||||
- `PUT /api/model/provider/{id}` - Update memory provider configuration
|
||||
- `DELETE /api/model/provider/{id}` - Remove memory provider
|
||||
|
||||
### Agent Memory Management
|
||||
- `GET /api/agent/{id}` - Get agent details including memory settings
|
||||
- `PUT /api/agent/{id}` - Update agent including memory configuration
|
||||
- `PUT /api/agent/saveMemory/{macAddress}` - Update memory by device MAC
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Model Provider Table
|
||||
```sql
|
||||
CREATE TABLE model_provider (
|
||||
id BIGINT PRIMARY KEY,
|
||||
model_type VARCHAR(50), -- 'Memory' for memory providers
|
||||
provider_code VARCHAR(100), -- 'mem0ai'
|
||||
name VARCHAR(255),
|
||||
fields TEXT, -- JSON configuration
|
||||
sort INT
|
||||
);
|
||||
```
|
||||
|
||||
### Agent Table
|
||||
```sql
|
||||
CREATE TABLE agent (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
summary_memory TEXT, -- Memory configuration prompt
|
||||
-- other fields...
|
||||
);
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Memory Prompt Design
|
||||
Create effective summary memory prompts:
|
||||
```text
|
||||
"Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories. Focus on:
|
||||
- User preferences and habits
|
||||
- Important personal information
|
||||
- Conversation context and history
|
||||
- Task-specific knowledge
|
||||
Summarize in a way that enables personalized and contextual responses."
|
||||
```
|
||||
|
||||
### 2. API Key Security
|
||||
- Store API keys securely in the database
|
||||
- Never expose keys in logs or responses
|
||||
- Use environment variables for production deployments
|
||||
|
||||
### 3. Memory Management
|
||||
- Regularly review and update memory prompts
|
||||
- Monitor memory usage through Mem0 dashboard
|
||||
- Clean up outdated memories periodically
|
||||
|
||||
### 4. Error Handling
|
||||
The system includes robust error handling:
|
||||
- Gracefully handles missing API keys
|
||||
- Falls back to no-memory mode if service unavailable
|
||||
- Logs errors for debugging without exposing sensitive data
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Memory not saving**
|
||||
- Check API key configuration
|
||||
- Verify mem0ai service is accessible
|
||||
- Check logs in `tmp/server.log`
|
||||
|
||||
2. **No memories returned**
|
||||
- Ensure agent has role_id configured
|
||||
- Verify memories exist for the user
|
||||
- Check query format and parameters
|
||||
|
||||
3. **Configuration not appearing**
|
||||
- Restart the xiaozhi-server after configuration changes
|
||||
- Verify database changes are committed
|
||||
- Check provider is enabled in selected_modules
|
||||
|
||||
### Debug Mode
|
||||
Enable debug logging to see memory operations:
|
||||
```yaml
|
||||
# In config.yaml
|
||||
log:
|
||||
log_level: DEBUG
|
||||
```
|
||||
|
||||
## Example Integration
|
||||
|
||||
### Complete Setup Flow
|
||||
1. **Install dependencies**:
|
||||
```bash
|
||||
pip install mem0ai==0.1.62
|
||||
```
|
||||
|
||||
2. **Configure provider in dashboard**:
|
||||
- Navigate to Provider Management
|
||||
- Add mem0ai provider with API key
|
||||
|
||||
3. **Create agent with memory**:
|
||||
- Go to Agent Management
|
||||
- Create new agent
|
||||
- Enable memory and select mem0ai
|
||||
- Configure summary memory prompt
|
||||
|
||||
4. **Test memory functionality**:
|
||||
- Connect device to agent
|
||||
- Have conversations
|
||||
- Check Mem0 dashboard for saved memories
|
||||
- Test memory recall in subsequent conversations
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Custom Memory Formatting
|
||||
The system formats memories with timestamps:
|
||||
```python
|
||||
[2024-03-15 14:30:45] User prefers morning meetings
|
||||
[2024-03-14 10:15:23] User's favorite color is blue
|
||||
[2024-03-13 09:45:12] User works in software engineering
|
||||
```
|
||||
|
||||
### Memory Search
|
||||
Query specific memories:
|
||||
```python
|
||||
results = memory_provider.query_memory("user preferences")
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
Process multiple agents' memories:
|
||||
```python
|
||||
for agent in agents:
|
||||
memory_provider.role_id = agent.id
|
||||
await memory_provider.save_memory(messages)
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **API Key Protection**
|
||||
- Use environment variables
|
||||
- Encrypt keys in database
|
||||
- Rotate keys regularly
|
||||
|
||||
2. **Data Privacy**
|
||||
- Mem0 stores data securely
|
||||
- Implement data retention policies
|
||||
- Provide user data export/deletion options
|
||||
|
||||
3. **Access Control**
|
||||
- Limit memory access by role
|
||||
- Audit memory operations
|
||||
- Implement rate limiting
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
1. **Caching**
|
||||
- Cache frequently accessed memories
|
||||
- Use Redis for temporary storage
|
||||
- Implement TTL for cache entries
|
||||
|
||||
2. **Batch Processing**
|
||||
- Group memory operations
|
||||
- Use async operations where possible
|
||||
- Implement queue for high-volume scenarios
|
||||
|
||||
3. **Monitoring**
|
||||
- Track memory API response times
|
||||
- Monitor error rates
|
||||
- Set up alerts for failures
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements for mem0 integration:
|
||||
- Local memory fallback option
|
||||
- Memory compression algorithms
|
||||
- Multi-agent memory sharing
|
||||
- Memory analytics dashboard
|
||||
- Automated memory pruning
|
||||
- Memory export/import tools
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
- Check logs in `tmp/server.log`
|
||||
- Review Mem0 documentation at https://docs.mem0.ai
|
||||
- Contact support with error details and configuration
|
||||
205
add_mem0_system_param.py
Normal file
205
add_mem0_system_param.py
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to add mem0.api_key system parameter
|
||||
This will bypass the API key masking issue
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
# Database configuration - from application-dev.yml
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
|
||||
'port': 25037, # Railway MySQL port
|
||||
'user': 'root', # Database username
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
|
||||
'database': 'railway', # Database name
|
||||
'charset': 'utf8mb4',
|
||||
'connect_timeout': 30, # Connection timeout in seconds
|
||||
'read_timeout': 30,
|
||||
'write_timeout': 30,
|
||||
'autocommit': False,
|
||||
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
|
||||
}
|
||||
|
||||
# The actual mem0 API key
|
||||
MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN"
|
||||
|
||||
# Colors for output
|
||||
class Colors:
|
||||
HEADER = '\033[95m'
|
||||
OKBLUE = '\033[94m'
|
||||
OKCYAN = '\033[96m'
|
||||
OKGREEN = '\033[92m'
|
||||
WARNING = '\033[93m'
|
||||
FAIL = '\033[91m'
|
||||
ENDC = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
|
||||
def print_header(text):
|
||||
"""Print a formatted header"""
|
||||
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
|
||||
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
|
||||
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
|
||||
|
||||
def print_success(text):
|
||||
"""Print success message"""
|
||||
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
|
||||
|
||||
def print_error(text):
|
||||
"""Print error message"""
|
||||
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
|
||||
|
||||
def print_info(text):
|
||||
"""Print info message"""
|
||||
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
|
||||
|
||||
def print_warning(text):
|
||||
"""Print warning message"""
|
||||
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the MySQL database"""
|
||||
try:
|
||||
print_info("Connecting to database...")
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
# Test the connection
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT 1")
|
||||
cursor.fetchone()
|
||||
|
||||
print_success("Successfully connected to database")
|
||||
return connection
|
||||
|
||||
except Exception as e:
|
||||
print_error(f"Failed to connect to database: {str(e)}")
|
||||
return None
|
||||
|
||||
def add_system_parameter(connection):
|
||||
"""Add mem0.api_key system parameter"""
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# Check if parameter already exists
|
||||
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
|
||||
existing = cursor.fetchone()
|
||||
|
||||
if existing:
|
||||
print_warning("Parameter mem0.api_key already exists:")
|
||||
print(f" Current value: {existing[2][:10]}...{existing[2][-10:] if len(existing[2]) > 20 else existing[2]}")
|
||||
|
||||
response = input(f"{Colors.WARNING}Do you want to update it? (yes/no): {Colors.ENDC}").lower()
|
||||
if response not in ['yes', 'y']:
|
||||
print_info("Skipping update")
|
||||
return True
|
||||
|
||||
# Update existing parameter
|
||||
update_query = """
|
||||
UPDATE sys_params
|
||||
SET param_value = %s,
|
||||
update_date = NOW(),
|
||||
updater = 1
|
||||
WHERE param_code = %s
|
||||
"""
|
||||
cursor.execute(update_query, (MEM0_API_KEY, 'mem0.api_key'))
|
||||
connection.commit()
|
||||
print_success("Updated existing mem0.api_key parameter")
|
||||
|
||||
else:
|
||||
# Get the next ID
|
||||
cursor.execute("SELECT MAX(id) FROM sys_params")
|
||||
max_id = cursor.fetchone()[0]
|
||||
next_id = (max_id or 0) + 1
|
||||
|
||||
# Insert new parameter
|
||||
insert_query = """
|
||||
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark, create_date, creator)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, NOW(), %s)
|
||||
"""
|
||||
|
||||
cursor.execute(insert_query, (
|
||||
next_id,
|
||||
'mem0.api_key',
|
||||
MEM0_API_KEY,
|
||||
'string',
|
||||
1, # param_type: 1 for system parameters
|
||||
'Mem0 AI API key for memory management',
|
||||
1 # creator: admin user
|
||||
))
|
||||
|
||||
connection.commit()
|
||||
print_success("Added new mem0.api_key system parameter")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
connection.rollback()
|
||||
print_error(f"Failed to add system parameter: {str(e)}")
|
||||
return False
|
||||
|
||||
def verify_parameter(connection):
|
||||
"""Verify the parameter was added correctly"""
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
print_success("Parameter verification successful:")
|
||||
print(f" ID: {result[0]}")
|
||||
print(f" Code: {result[1]}")
|
||||
print(f" Value: {result[2][:10]}...{result[2][-10:]}")
|
||||
print(f" Type: {result[3]}")
|
||||
print(f" Remark: {result[5]}")
|
||||
return True
|
||||
else:
|
||||
print_error("Parameter not found after insertion")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print_error(f"Failed to verify parameter: {str(e)}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
print_header("Add Mem0 API Key System Parameter")
|
||||
print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}")
|
||||
print_info(f"Timestamp: {datetime.now().isoformat()}")
|
||||
|
||||
# Connect to database
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
print_error("Cannot proceed without database connection")
|
||||
return 1
|
||||
|
||||
try:
|
||||
# Add system parameter
|
||||
if add_system_parameter(connection):
|
||||
# Verify the parameter
|
||||
if verify_parameter(connection):
|
||||
print_success("\n✅ System parameter added successfully!")
|
||||
print_info("\nNext steps:")
|
||||
print_info("1. Restart the manager-api service to load the new parameter")
|
||||
print_info("2. Test device connection again")
|
||||
print_info("3. Check that mem0 authentication now works")
|
||||
return 0
|
||||
else:
|
||||
return 1
|
||||
else:
|
||||
return 1
|
||||
|
||||
finally:
|
||||
connection.close()
|
||||
print_info("Database connection closed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
print("\n\nScript interrupted by user")
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
print_error(f"Unexpected error: {str(e)}")
|
||||
sys.exit(1)
|
||||
11
add_mqtt_params.sql
Normal file
11
add_mqtt_params.sql
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
-- Add MQTT configuration parameters to sys_params table
|
||||
-- Replace the values with your actual MQTT broker configuration
|
||||
|
||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (120, 'mqtt.broker', '139.59.7.72', 'string', 1, 'MQTT broker IP address');
|
||||
|
||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (121, 'mqtt.port', '1883', 'string', 1, 'MQTT broker port');
|
||||
|
||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (122, 'mqtt.signature_key', 'test-signature-key-12345', 'string', 1, 'MQTT signature key for authentication');
|
||||
197
add_mqtt_params_railway.py
Normal file
197
add_mqtt_params_railway.py
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script to add MQTT configuration parameters to Railway MySQL database
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
import sys
|
||||
import io
|
||||
from typing import Optional
|
||||
|
||||
# Set UTF-8 encoding for Windows console
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
|
||||
# Railway MySQL Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'database': 'railway',
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
# MQTT parameters to add
|
||||
MQTT_PARAMS = [
|
||||
{
|
||||
'id': 120,
|
||||
'param_code': 'mqtt.broker',
|
||||
'param_value': '192.168.1.107',
|
||||
'value_type': 'string',
|
||||
'param_type': 1,
|
||||
'remark': 'MQTT broker IP address'
|
||||
},
|
||||
{
|
||||
'id': 121,
|
||||
'param_code': 'mqtt.port',
|
||||
'param_value': '1883',
|
||||
'value_type': 'string',
|
||||
'param_type': 1,
|
||||
'remark': 'MQTT broker port'
|
||||
},
|
||||
{
|
||||
'id': 122,
|
||||
'param_code': 'mqtt.signature_key',
|
||||
'param_value': 'test-signature-key-12345',
|
||||
'value_type': 'string',
|
||||
'param_type': 1,
|
||||
'remark': 'MQTT signature key for authentication'
|
||||
}
|
||||
]
|
||||
|
||||
def connect_to_db():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
print(f"✅ Connected to Railway MySQL database")
|
||||
return connection
|
||||
except pymysql.Error as e:
|
||||
print(f"❌ Failed to connect to database: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
def check_existing_params(cursor, param_code: str) -> Optional[dict]:
|
||||
"""Check if a parameter already exists"""
|
||||
query = "SELECT * FROM sys_params WHERE param_code = %s"
|
||||
cursor.execute(query, (param_code,))
|
||||
result = cursor.fetchone()
|
||||
return result
|
||||
|
||||
def get_next_available_id(cursor) -> int:
|
||||
"""Get the next available ID for sys_params table"""
|
||||
query = "SELECT MAX(id) as max_id FROM sys_params"
|
||||
cursor.execute(query)
|
||||
result = cursor.fetchone()
|
||||
if result and result['max_id']:
|
||||
return result['max_id'] + 1
|
||||
return 120 # Start from 120 if table is empty
|
||||
|
||||
def insert_or_update_param(cursor, param: dict) -> bool:
|
||||
"""Insert a new parameter or update existing one"""
|
||||
try:
|
||||
# First check if it already exists
|
||||
existing = check_existing_params(cursor, param['param_code'])
|
||||
if existing:
|
||||
print(f"⚠️ Parameter '{param['param_code']}' already exists with value: {existing['param_value']}")
|
||||
|
||||
# Update the existing parameter
|
||||
update_query = """
|
||||
UPDATE sys_params
|
||||
SET param_value = %s, remark = %s
|
||||
WHERE param_code = %s
|
||||
"""
|
||||
cursor.execute(update_query, (param['param_value'], param['remark'], param['param_code']))
|
||||
print(f" ✅ Updated parameter '{param['param_code']}' to: {param['param_value']}")
|
||||
return True
|
||||
|
||||
# Get next available ID if the specified one is taken
|
||||
check_id_query = "SELECT id FROM sys_params WHERE id = %s"
|
||||
cursor.execute(check_id_query, (param['id'],))
|
||||
if cursor.fetchone():
|
||||
param['id'] = get_next_available_id(cursor)
|
||||
print(f" ℹ️ Using ID {param['id']} for '{param['param_code']}'")
|
||||
|
||||
# Insert new parameter
|
||||
insert_query = """
|
||||
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
cursor.execute(insert_query, (
|
||||
param['id'],
|
||||
param['param_code'],
|
||||
param['param_value'],
|
||||
param['value_type'],
|
||||
param['param_type'],
|
||||
param['remark']
|
||||
))
|
||||
print(f"✅ Added parameter '{param['param_code']}' with value: {param['param_value']}")
|
||||
return True
|
||||
except pymysql.Error as e:
|
||||
print(f"❌ Failed to insert/update '{param['param_code']}': {e}")
|
||||
return False
|
||||
|
||||
def verify_params(cursor):
|
||||
"""Verify that all MQTT parameters are in the database"""
|
||||
print("\n📋 Current MQTT parameters in database:")
|
||||
print("-" * 50)
|
||||
query = "SELECT param_code, param_value, remark FROM sys_params WHERE param_code LIKE 'mqtt.%' ORDER BY param_code"
|
||||
cursor.execute(query)
|
||||
results = cursor.fetchall()
|
||||
|
||||
if results:
|
||||
for row in results:
|
||||
print(f" • {row['param_code']}: {row['param_value']}")
|
||||
print(f" ({row['remark']})")
|
||||
else:
|
||||
print(" No MQTT parameters found")
|
||||
|
||||
return len(results) > 0
|
||||
|
||||
def main():
|
||||
print("🔧 Railway MySQL - MQTT Parameter Configuration Tool")
|
||||
print("=" * 60)
|
||||
print(f"📍 Connecting to: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
|
||||
print(f"📦 Database: {DB_CONFIG['database']}")
|
||||
print("=" * 60)
|
||||
|
||||
# Connect to database
|
||||
connection = connect_to_db()
|
||||
|
||||
try:
|
||||
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
|
||||
print("\n📝 Adding/Updating MQTT parameters...")
|
||||
print("-" * 50)
|
||||
|
||||
# Add each parameter
|
||||
changes_made = False
|
||||
for param in MQTT_PARAMS:
|
||||
if insert_or_update_param(cursor, param):
|
||||
changes_made = True
|
||||
|
||||
# Commit changes
|
||||
if changes_made:
|
||||
connection.commit()
|
||||
print("\n✅ All changes committed to database")
|
||||
else:
|
||||
print("\n⚠️ No changes were made")
|
||||
|
||||
# Verify parameters
|
||||
verify_params(cursor)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ MQTT parameters configuration complete!")
|
||||
print("\n⚠️ IMPORTANT NEXT STEPS:")
|
||||
print(" 1. Restart the manager-api server for changes to take effect")
|
||||
print(" 2. The ESP32 device should now receive MQTT configuration")
|
||||
print(" 3. The Python client should also connect successfully")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ An error occurred: {e}")
|
||||
connection.rollback()
|
||||
finally:
|
||||
connection.close()
|
||||
print("\n🔌 Database connection closed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("\n🚀 This script will configure MQTT parameters in your Railway MySQL database")
|
||||
print(" The following parameters will be added/updated:")
|
||||
print(" • mqtt.broker: 139.59.7.72")
|
||||
print(" • mqtt.port: 1883")
|
||||
print(" • mqtt.signature_key: test-signature-key-12345\n")
|
||||
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n❌ Operation cancelled by user")
|
||||
except Exception as e:
|
||||
print(f"\n❌ Unexpected error: {e}")
|
||||
186
check_database_structure.py
Normal file
186
check_database_structure.py
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to check the ai_model_provider table structure and existing ASR services
|
||||
"""
|
||||
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
import json
|
||||
from tabulate import tabulate
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(
|
||||
host='nozomi.proxy.rlwy.net',
|
||||
port=25037,
|
||||
database='railway',
|
||||
user='root',
|
||||
password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
charset='utf8mb4',
|
||||
use_unicode=True,
|
||||
ssl_disabled=True
|
||||
)
|
||||
|
||||
if connection.is_connected():
|
||||
print("Successfully connected to Railway MySQL database")
|
||||
return connection
|
||||
|
||||
except Error as e:
|
||||
print(f"Error connecting to MySQL: {e}")
|
||||
return None
|
||||
|
||||
def get_table_structure(connection, table_name):
|
||||
"""Get the structure of a table"""
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(f"DESCRIBE {table_name}")
|
||||
columns = cursor.fetchall()
|
||||
|
||||
print(f"\nStructure of table '{table_name}':")
|
||||
headers = ["Field", "Type", "Null", "Key", "Default", "Extra"]
|
||||
print(tabulate(columns, headers=headers, tablefmt="grid"))
|
||||
|
||||
return columns
|
||||
|
||||
except Error as e:
|
||||
print(f"Error getting table structure: {e}")
|
||||
return None
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def get_existing_asr_providers(connection):
|
||||
"""Get all existing ASR providers"""
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, model_type, provider_code, name, LENGTH(id) as id_length
|
||||
FROM ai_model_provider
|
||||
WHERE model_type = 'ASR'
|
||||
ORDER BY id
|
||||
""")
|
||||
providers = cursor.fetchall()
|
||||
|
||||
print(f"\nExisting ASR providers:")
|
||||
headers = ["ID", "Model Type", "Provider Code", "Name", "ID Length"]
|
||||
print(tabulate(providers, headers=headers, tablefmt="grid"))
|
||||
|
||||
return providers
|
||||
|
||||
except Error as e:
|
||||
print(f"Error getting ASR providers: {e}")
|
||||
return None
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def get_existing_asr_configs(connection):
|
||||
"""Get all existing ASR model configurations"""
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, model_type, model_code, model_name, LENGTH(id) as id_length
|
||||
FROM ai_model_config
|
||||
WHERE model_type = 'ASR'
|
||||
ORDER BY id
|
||||
""")
|
||||
configs = cursor.fetchall()
|
||||
|
||||
print(f"\nExisting ASR model configurations:")
|
||||
headers = ["ID", "Model Type", "Model Code", "Model Name", "ID Length"]
|
||||
print(tabulate(configs, headers=headers, tablefmt="grid"))
|
||||
|
||||
return configs
|
||||
|
||||
except Error as e:
|
||||
print(f"Error getting ASR configs: {e}")
|
||||
return None
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def analyze_id_constraints(providers, configs):
|
||||
"""Analyze ID length constraints"""
|
||||
print(f"\nID Length Analysis:")
|
||||
|
||||
if providers:
|
||||
provider_lengths = [row[4] for row in providers] # ID length is 5th column
|
||||
print(f"Provider ID lengths: {provider_lengths}")
|
||||
print(f"Max provider ID length: {max(provider_lengths)}")
|
||||
print(f"Min provider ID length: {min(provider_lengths)}")
|
||||
|
||||
if configs:
|
||||
config_lengths = [row[4] for row in configs] # ID length is 5th column
|
||||
print(f"Config ID lengths: {config_lengths}")
|
||||
print(f"Max config ID length: {max(config_lengths)}")
|
||||
print(f"Min config ID length: {min(config_lengths)}")
|
||||
|
||||
# Check our proposed ID
|
||||
proposed_provider_id = "SYSTEM_ASR_AmazonTranscribeStreaming"
|
||||
proposed_config_id = "ASR_AmazonTranscribeStreaming"
|
||||
|
||||
print(f"\nOur proposed IDs:")
|
||||
print(f"Provider ID: '{proposed_provider_id}' (length: {len(proposed_provider_id)})")
|
||||
print(f"Config ID: '{proposed_config_id}' (length: {len(proposed_config_id)})")
|
||||
|
||||
if providers and len(proposed_provider_id) > max(provider_lengths):
|
||||
print(f"WARNING: Proposed provider ID is longer than existing max ({max(provider_lengths)})")
|
||||
|
||||
if configs and len(proposed_config_id) > max(config_lengths):
|
||||
print(f"WARNING: Proposed config ID is longer than existing max ({max(config_lengths)})")
|
||||
|
||||
def suggest_shorter_ids():
|
||||
"""Suggest shorter ID alternatives"""
|
||||
print(f"\nSuggested shorter IDs:")
|
||||
|
||||
alternatives = [
|
||||
("SYSTEM_ASR_AmazonTS", "ASR_AmazonTS"),
|
||||
("SYSTEM_ASR_AwsTranscribe", "ASR_AwsTranscribe"),
|
||||
("SYSTEM_ASR_AmazonStream", "ASR_AmazonStream"),
|
||||
("SYSTEM_ASR_AWSStream", "ASR_AWSStream"),
|
||||
]
|
||||
|
||||
headers = ["Provider ID", "Config ID", "Provider Length", "Config Length"]
|
||||
rows = []
|
||||
for provider_id, config_id in alternatives:
|
||||
rows.append([provider_id, config_id, len(provider_id), len(config_id)])
|
||||
|
||||
print(tabulate(rows, headers=headers, tablefmt="grid"))
|
||||
|
||||
def main():
|
||||
print("Checking xiaozhi database structure for Amazon Transcribe integration")
|
||||
print("=" * 70)
|
||||
|
||||
# Connect to database
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# Get table structures
|
||||
print("\n" + "="*50)
|
||||
provider_structure = get_table_structure(connection, "ai_model_provider")
|
||||
|
||||
print("\n" + "="*50)
|
||||
config_structure = get_table_structure(connection, "ai_model_config")
|
||||
|
||||
# Get existing ASR services
|
||||
print("\n" + "="*50)
|
||||
providers = get_existing_asr_providers(connection)
|
||||
|
||||
print("\n" + "="*50)
|
||||
configs = get_existing_asr_configs(connection)
|
||||
|
||||
# Analyze constraints
|
||||
print("\n" + "="*50)
|
||||
analyze_id_constraints(providers, configs)
|
||||
|
||||
# Suggest alternatives
|
||||
print("\n" + "="*50)
|
||||
suggest_shorter_ids()
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
print(f"\nMySQL connection closed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
5
check_mqtt_params.sql
Normal file
5
check_mqtt_params.sql
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
-- Check current MQTT-related parameters in sys_params table
|
||||
SELECT * FROM sys_params WHERE param_code LIKE 'mqtt.%';
|
||||
|
||||
-- Check all system parameters to see what's configured
|
||||
SELECT id, param_code, param_value, remark FROM sys_params ORDER BY id;
|
||||
178
check_system_params.py
Normal file
178
check_system_params.py
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to check system parameters table for mem0.api_key
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
# Database configuration - from application-dev.yml
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
|
||||
'port': 25037, # Railway MySQL port
|
||||
'user': 'root', # Database username
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
|
||||
'database': 'railway', # Database name
|
||||
'charset': 'utf8mb4',
|
||||
'connect_timeout': 30, # Connection timeout in seconds
|
||||
'read_timeout': 30,
|
||||
'write_timeout': 30,
|
||||
'autocommit': False,
|
||||
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
|
||||
}
|
||||
|
||||
# Colors for output
|
||||
class Colors:
|
||||
HEADER = '\033[95m'
|
||||
OKBLUE = '\033[94m'
|
||||
OKCYAN = '\033[96m'
|
||||
OKGREEN = '\033[92m'
|
||||
WARNING = '\033[93m'
|
||||
FAIL = '\033[91m'
|
||||
ENDC = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
|
||||
def print_header(text):
|
||||
"""Print a formatted header"""
|
||||
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
|
||||
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
|
||||
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
|
||||
|
||||
def print_success(text):
|
||||
"""Print success message"""
|
||||
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
|
||||
|
||||
def print_error(text):
|
||||
"""Print error message"""
|
||||
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
|
||||
|
||||
def print_info(text):
|
||||
"""Print info message"""
|
||||
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
|
||||
|
||||
def print_warning(text):
|
||||
"""Print warning message"""
|
||||
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the MySQL database"""
|
||||
try:
|
||||
print_info("Connecting to database...")
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
# Test the connection
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT 1")
|
||||
cursor.fetchone()
|
||||
|
||||
print_success("Successfully connected to database")
|
||||
return connection
|
||||
|
||||
except Exception as e:
|
||||
print_error(f"Failed to connect to database: {str(e)}")
|
||||
return None
|
||||
|
||||
def check_system_params(connection):
|
||||
"""Check system parameters table for mem0.api_key"""
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
# First, let's see what tables exist
|
||||
print_info("Checking available tables...")
|
||||
cursor.execute("SHOW TABLES LIKE '%param%'")
|
||||
param_tables = cursor.fetchall()
|
||||
|
||||
if param_tables:
|
||||
print_success(f"Found parameter-related tables:")
|
||||
for table in param_tables:
|
||||
print(f" - {table[0]}")
|
||||
|
||||
# Try different possible table names
|
||||
possible_tables = [
|
||||
'sys_params',
|
||||
'system_params',
|
||||
'sys_parameters',
|
||||
'system_parameters',
|
||||
'config_params',
|
||||
'application_params'
|
||||
]
|
||||
|
||||
found_table = None
|
||||
for table_name in possible_tables:
|
||||
try:
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
|
||||
found_table = table_name
|
||||
print_success(f"Found system parameters table: {table_name}")
|
||||
break
|
||||
except pymysql.err.ProgrammingError:
|
||||
continue
|
||||
|
||||
if found_table:
|
||||
# First, check the table structure
|
||||
cursor.execute(f"DESCRIBE {found_table}")
|
||||
columns = cursor.fetchall()
|
||||
print_info(f"Table structure for {found_table}:")
|
||||
for col in columns:
|
||||
print(f" {col[0]} ({col[1]})")
|
||||
|
||||
# Show all parameters for context
|
||||
cursor.execute(f"SELECT * FROM {found_table} LIMIT 10")
|
||||
all_params = cursor.fetchall()
|
||||
print_info(f"\nFirst 10 parameters in {found_table}:")
|
||||
for row in all_params:
|
||||
print(f" Row: {row}")
|
||||
|
||||
# Try to find mem0 parameter based on actual column structure
|
||||
if columns:
|
||||
# Assume first column is key, second is value
|
||||
key_col = columns[0][0]
|
||||
|
||||
query = f"SELECT * FROM {found_table} WHERE {key_col} = %s OR {key_col} LIKE %s"
|
||||
cursor.execute(query, ('mem0.api_key', '%mem0%'))
|
||||
results = cursor.fetchall()
|
||||
|
||||
if results:
|
||||
print_success("Found mem0-related parameters:")
|
||||
for row in results:
|
||||
print(f" Row: {row}")
|
||||
else:
|
||||
print_warning("No mem0.api_key parameter found in system parameters")
|
||||
|
||||
else:
|
||||
print_warning("No system parameters table found")
|
||||
print_info("Available tables:")
|
||||
cursor.execute("SHOW TABLES")
|
||||
all_tables = cursor.fetchall()
|
||||
for table in all_tables:
|
||||
print(f" - {table[0]}")
|
||||
|
||||
except Exception as e:
|
||||
print_error(f"Failed to check system parameters: {str(e)}")
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
print_header("System Parameters Check Script")
|
||||
print_info(f"Timestamp: {datetime.now().isoformat()}")
|
||||
|
||||
# Connect to database
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
print_error("Cannot proceed without database connection")
|
||||
return 1
|
||||
|
||||
try:
|
||||
check_system_params(connection)
|
||||
finally:
|
||||
connection.close()
|
||||
print_info("Database connection closed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
print("\n\nScript interrupted by user")
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
print_error(f"Unexpected error: {str(e)}")
|
||||
sys.exit(1)
|
||||
39
clear_redis.py
Normal file
39
clear_redis.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import redis
|
||||
|
||||
# Redis connection configuration
|
||||
redis_client = redis.Redis(
|
||||
host='maglev.proxy.rlwy.net',
|
||||
port=16780,
|
||||
password='beVfOKcZjMUCBiZIQnvSMivhpSeijpKP',
|
||||
username='default',
|
||||
db=0,
|
||||
decode_responses=True
|
||||
)
|
||||
|
||||
try:
|
||||
print("Connecting to Redis...")
|
||||
# Test connection
|
||||
redis_client.ping()
|
||||
print("Successfully connected to Redis!")
|
||||
|
||||
# Get all keys to see what's cached
|
||||
keys = redis_client.keys('*')
|
||||
print(f"Found {len(keys)} keys in Redis:")
|
||||
for key in keys[:10]: # Show first 10 keys
|
||||
print(f" - {key}")
|
||||
|
||||
if len(keys) > 10:
|
||||
print(f" ... and {len(keys) - 10} more keys")
|
||||
|
||||
# Clear all data in current database
|
||||
result = redis_client.flushdb()
|
||||
print(f"Redis cache cleared: {result}")
|
||||
|
||||
# Verify it's cleared
|
||||
keys_after = redis_client.keys('*')
|
||||
print(f"Keys remaining after clear: {len(keys_after)}")
|
||||
|
||||
except redis.exceptions.ConnectionError as e:
|
||||
print(f"Failed to connect to Redis: {e}")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
67
fix_migration.sql
Normal file
67
fix_migration.sql
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
-- Clear Liquibase lock and failed changesets
|
||||
DELETE FROM DATABASECHANGELOGLOCK WHERE ID = 1;
|
||||
|
||||
-- Mark the failed changeset as already executed (skip it)
|
||||
INSERT INTO DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, EXECTYPE, MD5SUM, DESCRIPTION, COMMENTS, TAG, LIQUIBASE, CONTEXTS, LABELS, DEPLOYMENT_ID)
|
||||
SELECT '202501230004_translate_model_names', 'cheeko', 'db/changelog/db.changelog-master.yaml', NOW(),
|
||||
(SELECT COALESCE(MAX(ORDEREXECUTED), 0) + 1 FROM DATABASECHANGELOG d), 'EXECUTED', 'placeholder',
|
||||
'Manual fix for column name issue', 'Manually fixed', NULL, '4.20.0', NULL, NULL,
|
||||
CONCAT(UNIX_TIMESTAMP(NOW()), '000')
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM DATABASECHANGELOG
|
||||
WHERE ID = '202501230004_translate_model_names'
|
||||
AND AUTHOR = 'cheeko'
|
||||
AND FILENAME = 'db/changelog/db.changelog-master.yaml'
|
||||
);
|
||||
|
||||
-- Apply the translations manually with correct column names
|
||||
UPDATE ai_model_provider SET name = 'SileroVAD Voice Activity Detection' WHERE name = 'SileroVAD语音活动检测';
|
||||
UPDATE ai_model_provider SET name = 'FunASR Speech Recognition' WHERE name = 'FunASR语音识别';
|
||||
UPDATE ai_model_provider SET name = 'SherpaASR Speech Recognition' WHERE name = 'SherpaASR语音识别';
|
||||
UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition' WHERE name = '火山引擎语音识别';
|
||||
UPDATE ai_model_provider SET name = 'Tencent Speech Recognition' WHERE name = '腾讯语音识别';
|
||||
UPDATE ai_model_provider SET name = 'Tencent Speech Synthesis' WHERE name = '腾讯语音合成';
|
||||
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition' WHERE name = '阿里云语音识别';
|
||||
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition (Streaming)' WHERE name = '阿里云语音识别(流式)';
|
||||
UPDATE ai_model_provider SET name = 'Baidu Speech Recognition' WHERE name = '百度语音识别';
|
||||
UPDATE ai_model_provider SET name = 'OpenAI Speech Recognition' WHERE name = 'OpenAI语音识别';
|
||||
UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition (Streaming)' WHERE name = '火山引擎语音识别(流式)';
|
||||
UPDATE ai_model_provider SET name = 'Alibaba Bailian Interface' WHERE name = '阿里百炼接口';
|
||||
UPDATE ai_model_provider SET name = 'Volcano Engine LLM' WHERE name = '火山引擎LLM';
|
||||
UPDATE ai_model_provider SET name = 'Volcano Engine TTS' WHERE name = '火山引擎TTS';
|
||||
UPDATE ai_model_provider SET name = 'Alibaba Cloud TTS' WHERE name = '阿里云TTS';
|
||||
UPDATE ai_model_provider SET name = 'Volcano Dual-Stream Speech Synthesis' WHERE name = '火山双流式语音合成';
|
||||
UPDATE ai_model_provider SET name = 'Linkerai Speech Synthesis' WHERE name = 'Linkerai语音合成';
|
||||
UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Synthesis (Streaming)' WHERE name = '阿里云语音合成(流式)';
|
||||
UPDATE ai_model_provider SET name = 'Index-TTS-vLLM Streaming Speech Synthesis' WHERE name = 'Index-TTS-vLLM流式语音合成';
|
||||
UPDATE ai_model_provider SET name = 'Mem0AI Memory' WHERE name = 'Mem0AI记忆';
|
||||
UPDATE ai_model_provider SET name = 'No Memory' WHERE name = '无记忆';
|
||||
UPDATE ai_model_provider SET name = 'Local Short Memory' WHERE name = '本地短记忆';
|
||||
UPDATE ai_model_provider SET name = 'No Intent Recognition' WHERE name = '无意图识别';
|
||||
UPDATE ai_model_provider SET name = 'LLM Intent Recognition' WHERE name = 'LLM意图识别';
|
||||
UPDATE ai_model_provider SET name = 'Function Call Intent Recognition' WHERE name = '函数调用意图识别';
|
||||
UPDATE ai_model_provider SET name = 'FunASR Server Speech Recognition' WHERE name = 'FunASR服务语音识别';
|
||||
UPDATE ai_model_provider SET name = 'MiniMax Speech Synthesis' WHERE name = 'MiniMax语音合成';
|
||||
UPDATE ai_model_provider SET name = 'OpenAI Speech Synthesis' WHERE name = 'OpenAI语音合成';
|
||||
|
||||
-- Update model config names
|
||||
UPDATE ai_model_config SET model_name = 'Zhipu AI' WHERE model_name = '智谱AI';
|
||||
UPDATE ai_model_config SET model_name = 'Tongyi Qianwen' WHERE model_name = '通义千问';
|
||||
UPDATE ai_model_config SET model_name = 'Tongyi Bailian' WHERE model_name = '通义百炼';
|
||||
UPDATE ai_model_config SET model_name = 'Doubao Large Model' WHERE model_name = '豆包大模型';
|
||||
UPDATE ai_model_config SET model_name = 'Google Gemini' WHERE model_name = '谷歌Gemini';
|
||||
UPDATE ai_model_config SET model_name = 'Tencent Speech Recognition' WHERE model_name = '腾讯语音识别';
|
||||
UPDATE ai_model_config SET model_name = 'Alibaba Cloud Speech Recognition' WHERE model_name = '阿里云语音识别';
|
||||
UPDATE ai_model_config SET model_name = 'Baidu Speech Recognition' WHERE model_name = '百度语音识别';
|
||||
UPDATE ai_model_config SET model_name = 'MiniMax Speech Synthesis' WHERE model_name = 'MiniMax语音合成';
|
||||
UPDATE ai_model_config SET model_name = 'OpenAI Speech Synthesis' WHERE model_name = 'OpenAI语音合成';
|
||||
UPDATE ai_model_config SET model_name = 'Volcano Dual-Stream Speech Synthesis' WHERE model_name = '火山双流式语音合成';
|
||||
UPDATE ai_model_config SET model_name = 'Linkerai Speech Synthesis' WHERE model_name = 'Linkerai语音合成';
|
||||
UPDATE ai_model_config SET model_name = 'Mem0AI Memory' WHERE model_name = 'Mem0AI记忆';
|
||||
UPDATE ai_model_config SET model_name = 'Function Call Intent Recognition' WHERE model_name = '函数调用意图识别';
|
||||
UPDATE ai_model_config SET model_name = 'Zhipu Visual AI' WHERE model_name = '智谱视觉AI';
|
||||
UPDATE ai_model_config SET model_name = 'Qianwen Visual Model' WHERE model_name = '千问视觉模型';
|
||||
UPDATE ai_model_config SET model_name = 'Volcano Edge Large Model Gateway' WHERE model_name = '火山引擎边缘大模型网关';
|
||||
|
||||
-- Update TTS voice names (correct column name)
|
||||
UPDATE ai_tts_voice SET name = 'Alibaba Cloud Xiaoyun' WHERE name = '阿里云小云';
|
||||
|
|
@ -1,7 +1,12 @@
|
|||
This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
|
||||
This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-documentation)
|
||||
|
||||
# Project Introduction
|
||||
|
||||
|
||||
run app
|
||||
|
||||
|
||||
npm run serve
|
||||
manager-api: This project is developed based on the SpringBoot framework.
|
||||
|
||||
When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project.
|
||||
|
|
@ -16,7 +21,7 @@ Vue 3.x
|
|||
# API Documentation
|
||||
After starting, open: http://localhost:8002/xiaozhi/doc.html
|
||||
|
||||
run app
|
||||
to run app
|
||||
|
||||
|
||||
npm run serve
|
||||
mvn spring-boot:run
|
||||
|
|
@ -8,8 +8,8 @@ import io.swagger.v3.oas.models.OpenAPI;
|
|||
import io.swagger.v3.oas.models.info.Info;
|
||||
|
||||
/**
|
||||
* Swagger配置
|
||||
* Copyright (c) 人人开源 All rights reserved.
|
||||
* Swagger Configuration
|
||||
* Copyright (c) RenRen Open Source All rights reserved.
|
||||
* Website: https://www.renren.io
|
||||
*/
|
||||
@Configuration
|
||||
|
|
@ -82,8 +82,8 @@ public class SwaggerConfig {
|
|||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI().info(new Info()
|
||||
.title("xiaozhi-esp32-manager-api")
|
||||
.description("xiaozhi-esp32-manager-api文档")
|
||||
.title("Xiaozhi ESP32 Manager API")
|
||||
.description("Xiaozhi ESP32 Manager API Documentation")
|
||||
.version("3.0")
|
||||
.termsOfService("https://127.0.0.1"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -242,7 +242,7 @@ public interface Constant {
|
|||
/**
|
||||
* 无效固件URL
|
||||
*/
|
||||
String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL";
|
||||
String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/toy/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL";
|
||||
|
||||
/**
|
||||
* 字典类型
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import xiaozhi.common.utils.Result;
|
|||
import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO;
|
||||
import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService;
|
||||
|
||||
@Tag(name = "智能体聊天历史管理")
|
||||
@Tag(name = "Agent Chat History Management")
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/agent/chat-history")
|
||||
|
|
@ -27,7 +27,7 @@ public class AgentChatHistoryController {
|
|||
*
|
||||
* @param request 包含上传文件及相关信息的请求对象
|
||||
*/
|
||||
@Operation(summary = "小智服务聊天上报请求")
|
||||
@Operation(summary = "Xiaozhi service chat report request")
|
||||
@PostMapping("/report")
|
||||
public Result<Boolean> uploadFile(@Valid @RequestBody AgentChatHistoryReportDTO request) {
|
||||
Boolean result = agentChatHistoryBizService.report(request);
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ import xiaozhi.modules.device.entity.DeviceEntity;
|
|||
import xiaozhi.modules.device.service.DeviceService;
|
||||
import xiaozhi.modules.security.user.SecurityUser;
|
||||
|
||||
@Tag(name = "智能体管理")
|
||||
@Tag(name = "Agent Management")
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/agent")
|
||||
|
|
@ -67,7 +67,7 @@ public class AgentController {
|
|||
private final RedisUtils redisUtils;
|
||||
|
||||
@GetMapping("/list")
|
||||
@Operation(summary = "获取用户智能体列表")
|
||||
@Operation(summary = "Get user agents list")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<AgentDTO>> getUserAgents() {
|
||||
UserDetail user = SecurityUser.getUser();
|
||||
|
|
@ -76,7 +76,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/all")
|
||||
@Operation(summary = "智能体列表(管理员)")
|
||||
@Operation(summary = "Agent list (admin)")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({
|
||||
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
|
||||
|
|
@ -89,7 +89,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "获取智能体详情")
|
||||
@Operation(summary = "Get agent details")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) {
|
||||
AgentInfoVO agent = agentService.getAgentById(id);
|
||||
|
|
@ -97,7 +97,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "创建智能体")
|
||||
@Operation(summary = "Create agent")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<String> save(@RequestBody @Valid AgentCreateDTO dto) {
|
||||
String agentId = agentService.createAgent(dto);
|
||||
|
|
@ -105,7 +105,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@PutMapping("/saveMemory/{macAddress}")
|
||||
@Operation(summary = "根据设备id更新智能体")
|
||||
@Operation(summary = "Update agent by device ID")
|
||||
public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) {
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
|
||||
if (device == null) {
|
||||
|
|
@ -118,7 +118,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "更新智能体")
|
||||
@Operation(summary = "Update agent")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) {
|
||||
agentService.updateAgentById(id, dto);
|
||||
|
|
@ -126,7 +126,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除智能体")
|
||||
@Operation(summary = "Delete agent")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<Void> delete(@PathVariable String id) {
|
||||
// 先删除关联的设备
|
||||
|
|
@ -141,7 +141,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/template")
|
||||
@Operation(summary = "智能体模板模板列表")
|
||||
@Operation(summary = "Agent template list")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<AgentTemplateEntity>> templateList() {
|
||||
List<AgentTemplateEntity> list = agentTemplateService
|
||||
|
|
@ -169,7 +169,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}/sessions")
|
||||
@Operation(summary = "获取智能体会话列表")
|
||||
@Operation(summary = "Get agent sessions list")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
@Parameters({
|
||||
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
|
||||
|
|
@ -184,7 +184,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}/chat-history/{sessionId}")
|
||||
@Operation(summary = "获取智能体聊天记录")
|
||||
@Operation(summary = "Get agent chat history")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<AgentChatHistoryDTO>> getAgentChatHistory(
|
||||
@PathVariable("id") String id,
|
||||
|
|
@ -202,7 +202,7 @@ public class AgentController {
|
|||
return new Result<List<AgentChatHistoryDTO>>().ok(result);
|
||||
}
|
||||
@GetMapping("/{id}/chat-history/user")
|
||||
@Operation(summary = "获取智能体聊天记录(用户)")
|
||||
@Operation(summary = "Get agent chat history (user)")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentId(
|
||||
@PathVariable("id") String id) {
|
||||
|
|
@ -220,7 +220,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}/chat-history/audio")
|
||||
@Operation(summary = "获取音频内容")
|
||||
@Operation(summary = "Get audio content")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<String> getContentByAudioId(
|
||||
@PathVariable("id") String id) {
|
||||
|
|
@ -230,7 +230,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@PostMapping("/audio/{audioId}")
|
||||
@Operation(summary = "获取音频下载ID")
|
||||
@Operation(summary = "Get audio download ID")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<String> getAudioId(@PathVariable("audioId") String audioId) {
|
||||
byte[] audioData = agentChatAudioService.getAudio(audioId);
|
||||
|
|
@ -243,7 +243,7 @@ public class AgentController {
|
|||
}
|
||||
|
||||
@GetMapping("/play/{uuid}")
|
||||
@Operation(summary = "播放音频")
|
||||
@Operation(summary = "Play audio")
|
||||
public ResponseEntity<byte[]> playAudio(@PathVariable("uuid") String uuid) {
|
||||
|
||||
String audioId = (String) redisUtils.get(RedisKeys.getAgentAudioIdKey(uuid));
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
|
|||
import xiaozhi.modules.agent.service.AgentService;
|
||||
import xiaozhi.modules.security.user.SecurityUser;
|
||||
|
||||
@Tag(name = "智能体Mcp接入点管理")
|
||||
@Tag(name = "Agent MCP Access Point Management")
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/agent/mcp")
|
||||
|
|
@ -31,7 +31,7 @@ public class AgentMcpAccessPointController {
|
|||
* @param audioId 智能体id
|
||||
* @return 返回错误提醒或者Mcp接入点地址
|
||||
*/
|
||||
@Operation(summary = "获取智能体的Mcp接入点地址")
|
||||
@Operation(summary = "Get agent MCP access point address")
|
||||
@GetMapping("/address/{agentId}")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<String> getAgentMcpAccessAddress(@PathVariable("agentId") String agentId) {
|
||||
|
|
@ -49,7 +49,7 @@ public class AgentMcpAccessPointController {
|
|||
return new Result<String>().ok(agentMcpAccessAddress);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取智能体的Mcp工具列表")
|
||||
@Operation(summary = "Get agent MCP tools list")
|
||||
@GetMapping("/tools/{agentId}")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<String>> getAgentMcpToolsList(@PathVariable("agentId") String agentId) {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import xiaozhi.modules.config.service.ConfigService;
|
|||
*/
|
||||
@RestController
|
||||
@RequestMapping("config")
|
||||
@Tag(name = "参数管理")
|
||||
@Tag(name = "Parameter Management")
|
||||
@AllArgsConstructor
|
||||
public class ConfigController {
|
||||
private final ConfigService configService;
|
||||
|
|
|
|||
|
|
@ -398,6 +398,22 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
}
|
||||
if ("Memory".equals(modelTypes[i])) {
|
||||
Map<String, Object> map = (Map<String, Object>) model.getConfigJson();
|
||||
|
||||
// Fix for Memory configuration API key
|
||||
if ("mem0ai".equals(map.get("type"))) {
|
||||
// Always use the actual API key from system parameters for mem0
|
||||
String mem0ApiKey = sysParamsService.getValue("mem0.api_key", false);
|
||||
if (StringUtils.isNotBlank(mem0ApiKey)) {
|
||||
map.put("api_key", mem0ApiKey);
|
||||
System.out.println("[DEBUG] Using mem0 API key from system parameters");
|
||||
} else {
|
||||
// Fallback to the original logic
|
||||
String apiKey = (String) map.get("api_key");
|
||||
System.out.println("[DEBUG] No system parameter for mem0.api_key, using config value: " +
|
||||
(apiKey != null ? "(length: " + apiKey.length() + ")" : "null"));
|
||||
}
|
||||
}
|
||||
|
||||
if ("mem_local_short".equals(map.get("type"))) {
|
||||
memLocalShortLLMModelId = (String) map.get("llm");
|
||||
if (StringUtils.isNotBlank(memLocalShortLLMModelId)
|
||||
|
|
|
|||
|
|
@ -77,6 +77,12 @@ public class DeviceReportRespDTO {
|
|||
@Getter
|
||||
@Setter
|
||||
public static class Mqtt {
|
||||
@Schema(description = "MQTT服务器地址")
|
||||
private String broker;
|
||||
|
||||
@Schema(description = "MQTT服务器端口")
|
||||
private Integer port;
|
||||
|
||||
@Schema(description = "MQTT服务器端点")
|
||||
private String endpoint;
|
||||
|
||||
|
|
|
|||
|
|
@ -427,6 +427,8 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
|||
String password = Base64.getEncoder().encodeToString(signature);
|
||||
|
||||
// Set MQTT credentials
|
||||
mqtt.setBroker(mqttBroker);
|
||||
mqtt.setPort(Integer.parseInt(mqttPort));
|
||||
mqtt.setEndpoint(mqttBroker + ":" + mqttPort);
|
||||
mqtt.setClient_id(clientId);
|
||||
mqtt.setUsername(username);
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ import xiaozhi.modules.timbre.service.TimbreService;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/models")
|
||||
@Tag(name = "模型配置")
|
||||
@Tag(name = "Model Configuration")
|
||||
public class ModelController {
|
||||
|
||||
private final ModelProviderService modelProviderService;
|
||||
|
|
@ -40,7 +40,7 @@ public class ModelController {
|
|||
private final AgentTemplateService agentTemplateService;
|
||||
|
||||
@GetMapping("/names")
|
||||
@Operation(summary = "获取所有模型名称")
|
||||
@Operation(summary = "Get all model names")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<ModelBasicInfoDTO>> getModelNames(@RequestParam String modelType,
|
||||
@RequestParam(required = false) String modelName) {
|
||||
|
|
@ -49,7 +49,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@GetMapping("/llm/names")
|
||||
@Operation(summary = "获取LLM模型信息")
|
||||
@Operation(summary = "Get LLM model information")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<LlmModelBasicInfoDTO>> getLlmModelCodeList(@RequestParam(required = false) String modelName) {
|
||||
List<LlmModelBasicInfoDTO> llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName);
|
||||
|
|
@ -57,7 +57,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@GetMapping("/{modelType}/provideTypes")
|
||||
@Operation(summary = "获取模型供应器列表")
|
||||
@Operation(summary = "Get model provider list")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<List<ModelProviderDTO>> getModelProviderList(@PathVariable String modelType) {
|
||||
List<ModelProviderDTO> modelProviderDTOS = modelProviderService.getListByModelType(modelType);
|
||||
|
|
@ -65,7 +65,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
@Operation(summary = "获取模型配置列表")
|
||||
@Operation(summary = "Get model configuration list")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<PageData<ModelConfigDTO>> getModelConfigList(
|
||||
@RequestParam(required = true) String modelType,
|
||||
|
|
@ -77,7 +77,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@PostMapping("/{modelType}/{provideCode}")
|
||||
@Operation(summary = "新增模型配置")
|
||||
@Operation(summary = "Add model configuration")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<ModelConfigDTO> addModelConfig(@PathVariable String modelType,
|
||||
@PathVariable String provideCode,
|
||||
|
|
@ -88,7 +88,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@PutMapping("/{modelType}/{provideCode}/{id}")
|
||||
@Operation(summary = "编辑模型配置")
|
||||
@Operation(summary = "Edit model configuration")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<ModelConfigDTO> editModelConfig(@PathVariable String modelType,
|
||||
@PathVariable String provideCode,
|
||||
|
|
@ -100,7 +100,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Operation(summary = "删除模型配置")
|
||||
@Operation(summary = "Delete model configuration")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> deleteModelConfig(@PathVariable String id) {
|
||||
modelConfigService.delete(id);
|
||||
|
|
@ -108,7 +108,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "获取模型配置")
|
||||
@Operation(summary = "Get model configuration")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<ModelConfigDTO> getModelConfig(@PathVariable String id) {
|
||||
ModelConfigEntity item = modelConfigService.selectById(id);
|
||||
|
|
@ -117,7 +117,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@PutMapping("/enable/{id}/{status}")
|
||||
@Operation(summary = "启用/关闭模型配置")
|
||||
@Operation(summary = "Enable/disable model configuration")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> enableModelConfig(@PathVariable String id, @PathVariable Integer status) {
|
||||
ModelConfigEntity entity = modelConfigService.selectById(id);
|
||||
|
|
@ -130,7 +130,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@PutMapping("/default/{id}")
|
||||
@Operation(summary = "设置默认模型")
|
||||
@Operation(summary = "Set default model")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> setDefaultModel(@PathVariable String id) {
|
||||
ModelConfigEntity entity = modelConfigService.selectById(id);
|
||||
|
|
@ -151,7 +151,7 @@ public class ModelController {
|
|||
}
|
||||
|
||||
@GetMapping("/{modelId}/voices")
|
||||
@Operation(summary = "获取模型音色")
|
||||
@Operation(summary = "Get model voices")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<VoiceDTO>> getVoiceList(@PathVariable String modelId,
|
||||
@RequestParam(required = false) String voiceName) {
|
||||
|
|
|
|||
|
|
@ -26,13 +26,13 @@ import xiaozhi.modules.model.service.ModelProviderService;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/models/provider")
|
||||
@Tag(name = "模型供应器")
|
||||
@Tag(name = "Model Provider")
|
||||
public class ModelProviderController {
|
||||
|
||||
private final ModelProviderService modelProviderService;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "获取模型供应器列表")
|
||||
@Operation(summary = "Get model provider list")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<PageData<ModelProviderDTO>> getListPage(ModelProviderDTO modelProviderDTO,
|
||||
@RequestParam(required = true, defaultValue = "0") String page,
|
||||
|
|
@ -42,7 +42,7 @@ public class ModelProviderController {
|
|||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "新增模型供应器")
|
||||
@Operation(summary = "Add model provider")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<ModelProviderDTO> add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) {
|
||||
ModelProviderDTO resp = modelProviderService.add(modelProviderDTO);
|
||||
|
|
@ -50,7 +50,7 @@ public class ModelProviderController {
|
|||
}
|
||||
|
||||
@PutMapping
|
||||
@Operation(summary = "修改模型供应器")
|
||||
@Operation(summary = "Edit model provider")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<ModelProviderDTO> edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) {
|
||||
ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO);
|
||||
|
|
@ -58,7 +58,7 @@ public class ModelProviderController {
|
|||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "删除模型供应器")
|
||||
@Operation(summary = "Delete model provider")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameter(name = "ids", description = "ID数组", required = true)
|
||||
public Result<Void> delete(@RequestBody List<String> ids) {
|
||||
|
|
@ -67,7 +67,7 @@ public class ModelProviderController {
|
|||
}
|
||||
|
||||
@GetMapping("/plugin/names")
|
||||
@Tag(name = "获取插件名称列表")
|
||||
@Tag(name = "Get Plugin Name List")
|
||||
public Result<List<ModelProviderDTO>> getPluginNameList() {
|
||||
return ResultUtils.success(modelProviderService.getPluginList());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ import xiaozhi.modules.sys.vo.SysDictDataItem;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
@Tag(name = "登录管理")
|
||||
@Tag(name = "Login Management")
|
||||
public class LoginController {
|
||||
private final SysUserService sysUserService;
|
||||
private final SysUserTokenService sysUserTokenService;
|
||||
|
|
@ -54,7 +54,7 @@ public class LoginController {
|
|||
private final SysDictDataService sysDictDataService;
|
||||
|
||||
@GetMapping("/captcha")
|
||||
@Operation(summary = "验证码")
|
||||
@Operation(summary = "Captcha")
|
||||
public void captcha(HttpServletResponse response, String uuid) throws IOException {
|
||||
// uuid不能为空
|
||||
AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
|
||||
|
|
@ -63,7 +63,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@PostMapping("/smsVerification")
|
||||
@Operation(summary = "短信验证码")
|
||||
@Operation(summary = "SMS verification code")
|
||||
public Result<Void> smsVerification(@RequestBody SmsVerificationDTO dto) {
|
||||
// 验证图形验证码
|
||||
boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), true);
|
||||
|
|
@ -81,7 +81,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
@Operation(summary = "登录")
|
||||
@Operation(summary = "Login")
|
||||
public Result<TokenDTO> login(@RequestBody LoginDTO login) {
|
||||
// 验证是否正确输入验证码
|
||||
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha(), true);
|
||||
|
|
@ -102,8 +102,10 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@Operation(summary = "注册")
|
||||
public Result<TokenDTO> register(@RequestBody LoginDTO login) {
|
||||
|
||||
@Operation(summary = "Register")
|
||||
public Result<Void> register(@RequestBody LoginDTO login) {
|
||||
Production1
|
||||
if (!sysUserService.getAllowUserRegister()) {
|
||||
throw new RenException("当前不允许普通用户注册");
|
||||
}
|
||||
|
|
@ -151,7 +153,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@GetMapping("/info")
|
||||
@Operation(summary = "用户信息获取")
|
||||
@Operation(summary = "Get user information")
|
||||
public Result<UserDetail> info() {
|
||||
UserDetail user = SecurityUser.getUser();
|
||||
Result<UserDetail> result = new Result<>();
|
||||
|
|
@ -160,7 +162,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@PutMapping("/change-password")
|
||||
@Operation(summary = "修改用户密码")
|
||||
@Operation(summary = "Change user password")
|
||||
public Result<?> changePassword(@RequestBody PasswordDTO passwordDTO) {
|
||||
// 判断非空
|
||||
ValidatorUtils.validateEntity(passwordDTO);
|
||||
|
|
@ -170,7 +172,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@PutMapping("/retrieve-password")
|
||||
@Operation(summary = "找回密码")
|
||||
@Operation(summary = "Retrieve password")
|
||||
public Result<?> retrievePassword(@RequestBody RetrievePasswordDTO dto) {
|
||||
// 是否开启手机注册
|
||||
Boolean isMobileRegister = sysParamsService
|
||||
|
|
@ -203,7 +205,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@GetMapping("/pub-config")
|
||||
@Operation(summary = "公共配置")
|
||||
@Operation(summary = "Public configuration")
|
||||
public Result<Map<String, Object>> pubConfig() {
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
config.put("enableMobileRegister", sysParamsService
|
||||
|
|
|
|||
|
|
@ -37,14 +37,14 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/admin")
|
||||
@Tag(name = "管理员管理")
|
||||
@Tag(name = "Administrator Management")
|
||||
public class AdminController {
|
||||
private final SysUserService sysUserService;
|
||||
|
||||
private final DeviceService deviceService;
|
||||
|
||||
@GetMapping("/users")
|
||||
@Operation(summary = "分页查找用户")
|
||||
@Operation(summary = "Paginated user search")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({
|
||||
@Parameter(name = "mobile", description = "用户手机号码", required = false),
|
||||
|
|
@ -63,7 +63,7 @@ public class AdminController {
|
|||
}
|
||||
|
||||
@PutMapping("/users/{id}")
|
||||
@Operation(summary = "重置密码")
|
||||
@Operation(summary = "Reset password")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<String> update(
|
||||
@PathVariable Long id) {
|
||||
|
|
@ -72,7 +72,7 @@ public class AdminController {
|
|||
}
|
||||
|
||||
@DeleteMapping("/users/{id}")
|
||||
@Operation(summary = "用户删除")
|
||||
@Operation(summary = "Delete user")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> delete(@PathVariable Long id) {
|
||||
sysUserService.deleteById(id);
|
||||
|
|
@ -80,7 +80,7 @@ public class AdminController {
|
|||
}
|
||||
|
||||
@PutMapping("/users/changeStatus/{status}")
|
||||
@Operation(summary = "批量修改用户状态")
|
||||
@Operation(summary = "Batch modify user status")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameter(name = "status", description = "用户状态", required = true)
|
||||
public Result<Void> changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) {
|
||||
|
|
@ -89,7 +89,7 @@ public class AdminController {
|
|||
}
|
||||
|
||||
@GetMapping("/device/all")
|
||||
@Operation(summary = "分页查找设备")
|
||||
@Operation(summary = "Paginated device search")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({
|
||||
@Parameter(name = "keywords", description = "设备关键词", required = false),
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ import xiaozhi.modules.sys.utils.WebSocketClientManager;
|
|||
*/
|
||||
@RestController
|
||||
@RequestMapping("/admin/server")
|
||||
@Tag(name = "服务端管理")
|
||||
@Tag(name = "Server Management")
|
||||
@AllArgsConstructor
|
||||
public class ServerSideManageController {
|
||||
private final SysParamsService sysParamsService;
|
||||
|
|
@ -47,7 +47,7 @@ public class ServerSideManageController {
|
|||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取Ws服务端列表")
|
||||
@Operation(summary = "Get WebSocket server list")
|
||||
@GetMapping("/server-list")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<List<String>> getWsServerList() {
|
||||
|
|
@ -58,7 +58,7 @@ public class ServerSideManageController {
|
|||
return new Result<List<String>>().ok(Arrays.asList(wsText.split(";")));
|
||||
}
|
||||
|
||||
@Operation(summary = "通知python服务端更新配置")
|
||||
@Operation(summary = "Notify Python server to update configuration")
|
||||
@PostMapping("/emit-action")
|
||||
@LogOperation("通知python服务端更新配置")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
|
|
|
|||
|
|
@ -37,12 +37,12 @@ import xiaozhi.modules.sys.vo.SysDictDataVO;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/admin/dict/data")
|
||||
@Tag(name = "字典数据管理")
|
||||
@Tag(name = "Dictionary Data Management")
|
||||
public class SysDictDataController {
|
||||
private final SysDictDataService sysDictDataService;
|
||||
|
||||
@GetMapping("/page")
|
||||
@Operation(summary = "分页查询字典数据")
|
||||
@Operation(summary = "Paginated dictionary data query")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({ @Parameter(name = "dictTypeId", description = "字典类型ID", required = true),
|
||||
@Parameter(name = "dictLabel", description = "数据标签"), @Parameter(name = "dictValue", description = "数据值"),
|
||||
|
|
@ -60,7 +60,7 @@ public class SysDictDataController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "获取字典数据详情")
|
||||
@Operation(summary = "Get dictionary data details")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<SysDictDataVO> get(@PathVariable("id") Long id) {
|
||||
SysDictDataVO vo = sysDictDataService.get(id);
|
||||
|
|
@ -68,7 +68,7 @@ public class SysDictDataController {
|
|||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
@Operation(summary = "新增字典数据")
|
||||
@Operation(summary = "Add dictionary data")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> save(@RequestBody SysDictDataDTO dto) {
|
||||
ValidatorUtils.validateEntity(dto);
|
||||
|
|
@ -77,7 +77,7 @@ public class SysDictDataController {
|
|||
}
|
||||
|
||||
@PutMapping("/update")
|
||||
@Operation(summary = "修改字典数据")
|
||||
@Operation(summary = "Modify dictionary data")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> update(@RequestBody SysDictDataDTO dto) {
|
||||
ValidatorUtils.validateEntity(dto);
|
||||
|
|
@ -86,7 +86,7 @@ public class SysDictDataController {
|
|||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "删除字典数据")
|
||||
@Operation(summary = "Delete dictionary data")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameter(name = "ids", description = "ID数组", required = true)
|
||||
public Result<Void> delete(@RequestBody Long[] ids) {
|
||||
|
|
@ -95,7 +95,7 @@ public class SysDictDataController {
|
|||
}
|
||||
|
||||
@GetMapping("/type/{dictType}")
|
||||
@Operation(summary = "获取字典数据列表")
|
||||
@Operation(summary = "Get dictionary data list")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<SysDictDataItem>> getDictDataByType(@PathVariable("dictType") String dictType) {
|
||||
List<SysDictDataItem> list = sysDictDataService.getDictDataByType(dictType);
|
||||
|
|
|
|||
|
|
@ -34,12 +34,12 @@ import xiaozhi.modules.sys.vo.SysDictTypeVO;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/admin/dict/type")
|
||||
@Tag(name = "字典类型管理")
|
||||
@Tag(name = "Dictionary Type Management")
|
||||
public class SysDictTypeController {
|
||||
private final SysDictTypeService sysDictTypeService;
|
||||
|
||||
@GetMapping("/page")
|
||||
@Operation(summary = "分页查询字典类型")
|
||||
@Operation(summary = "Paginated dictionary type query")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({ @Parameter(name = "dictType", description = "字典类型编码"),
|
||||
@Parameter(name = "dictName", description = "字典类型名称"),
|
||||
|
|
@ -52,7 +52,7 @@ public class SysDictTypeController {
|
|||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Operation(summary = "获取字典类型详情")
|
||||
@Operation(summary = "Get dictionary type details")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<SysDictTypeVO> get(@PathVariable("id") Long id) {
|
||||
SysDictTypeVO vo = sysDictTypeService.get(id);
|
||||
|
|
@ -60,7 +60,7 @@ public class SysDictTypeController {
|
|||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
@Operation(summary = "保存字典类型")
|
||||
@Operation(summary = "Save dictionary type")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> save(@RequestBody SysDictTypeDTO dto) {
|
||||
// 参数校验
|
||||
|
|
@ -71,7 +71,7 @@ public class SysDictTypeController {
|
|||
}
|
||||
|
||||
@PutMapping("/update")
|
||||
@Operation(summary = "修改字典类型")
|
||||
@Operation(summary = "Modify dictionary type")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> update(@RequestBody SysDictTypeDTO dto) {
|
||||
// 参数校验
|
||||
|
|
@ -82,7 +82,7 @@ public class SysDictTypeController {
|
|||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "删除字典类型")
|
||||
@Operation(summary = "Delete dictionary type")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameter(name = "ids", description = "ID数组", required = true)
|
||||
public Result<Void> delete(@RequestBody Long[] ids) {
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ import xiaozhi.modules.sys.utils.WebSocketValidator;
|
|||
*/
|
||||
@RestController
|
||||
@RequestMapping("admin/params")
|
||||
@Tag(name = "参数管理")
|
||||
@Tag(name = "Parameter Management")
|
||||
@AllArgsConstructor
|
||||
public class SysParamsController {
|
||||
private final SysParamsService sysParamsService;
|
||||
|
|
@ -53,7 +53,7 @@ public class SysParamsController {
|
|||
private final RestTemplate restTemplate;
|
||||
|
||||
@GetMapping("page")
|
||||
@Operation(summary = "分页")
|
||||
@Operation(summary = "Pagination")
|
||||
@Parameters({
|
||||
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
|
||||
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
|
||||
|
|
@ -69,7 +69,7 @@ public class SysParamsController {
|
|||
}
|
||||
|
||||
@GetMapping("{id}")
|
||||
@Operation(summary = "信息")
|
||||
@Operation(summary = "Information")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<SysParamsDTO> get(@PathVariable("id") Long id) {
|
||||
SysParamsDTO data = sysParamsService.get(id);
|
||||
|
|
@ -78,7 +78,7 @@ public class SysParamsController {
|
|||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "保存")
|
||||
@Operation(summary = "Save")
|
||||
@LogOperation("保存")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> save(@RequestBody SysParamsDTO dto) {
|
||||
|
|
@ -91,7 +91,7 @@ public class SysParamsController {
|
|||
}
|
||||
|
||||
@PutMapping
|
||||
@Operation(summary = "修改")
|
||||
@Operation(summary = "Modify")
|
||||
@LogOperation("修改")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> update(@RequestBody SysParamsDTO dto) {
|
||||
|
|
@ -150,7 +150,7 @@ public class SysParamsController {
|
|||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "删除")
|
||||
@Operation(summary = "Delete")
|
||||
@LogOperation("删除")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> delete(@RequestBody String[] ids) {
|
||||
|
|
|
|||
|
|
@ -35,12 +35,12 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
|
|||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/ttsVoice")
|
||||
@Tag(name = "音色管理")
|
||||
@Tag(name = "Timbre Management")
|
||||
public class TimbreController {
|
||||
private final TimbreService timbreService;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查找")
|
||||
@Operation(summary = "Paginated search")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
@Parameters({
|
||||
@Parameter(name = "ttsModelId", description = "对应 TTS 模型主键", required = true),
|
||||
|
|
@ -62,7 +62,7 @@ public class TimbreController {
|
|||
}
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "音色保存")
|
||||
@Operation(summary = "Save timbre")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> save(@RequestBody TimbreDataDTO dto) {
|
||||
ValidatorUtils.validateEntity(dto);
|
||||
|
|
@ -71,7 +71,7 @@ public class TimbreController {
|
|||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Operation(summary = "音色修改")
|
||||
@Operation(summary = "Modify timbre")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> update(
|
||||
@PathVariable String id,
|
||||
|
|
@ -82,7 +82,7 @@ public class TimbreController {
|
|||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "音色删除")
|
||||
@Operation(summary = "Delete timbre")
|
||||
@RequiresPermissions("sys:role:superAdmin")
|
||||
public Result<Void> delete(@RequestBody String[] ids) {
|
||||
timbreService.delete(ids);
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ server:
|
|||
min-spare: 30
|
||||
port: 8002
|
||||
servlet:
|
||||
context-path: /xiaozhi
|
||||
context-path: /toy
|
||||
session:
|
||||
cookie:
|
||||
http-only: true
|
||||
|
|
|
|||
|
|
@ -0,0 +1,7 @@
|
|||
-- Translate Chinese dictionary type names to English
|
||||
UPDATE `sys_dict_type` SET `dict_name` = 'Mobile Area' WHERE `dict_type` = 'MOBILE_AREA';
|
||||
UPDATE `sys_dict_type` SET `dict_name` = 'Firmware Type' WHERE `dict_type` = 'FIRMWARE_TYPE';
|
||||
|
||||
-- Also update remarks to English
|
||||
UPDATE `sys_dict_type` SET `remark` = 'Mobile area codes dictionary' WHERE `dict_type` = 'MOBILE_AREA';
|
||||
UPDATE `sys_dict_type` SET `remark` = 'Firmware types dictionary' WHERE `dict_type` = 'FIRMWARE_TYPE';
|
||||
|
|
@ -0,0 +1,401 @@
|
|||
-- Translate provider field labels from Chinese to English
|
||||
-- This will update the field labels shown in the Call Information section
|
||||
|
||||
-- Update common field labels across all providers
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"API密钥"', '"label":"API Key"')
|
||||
WHERE fields LIKE '%"label":"API密钥"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"服务地址"', '"label":"Service URL"')
|
||||
WHERE fields LIKE '%"label":"服务地址"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"基础URL"', '"label":"Base URL"')
|
||||
WHERE fields LIKE '%"label":"基础URL"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"模型名称"', '"label":"Model Name"')
|
||||
WHERE fields LIKE '%"label":"模型名称"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"输出目录"', '"label":"Output Directory"')
|
||||
WHERE fields LIKE '%"label":"输出目录"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"端口号"', '"label":"Port"')
|
||||
WHERE fields LIKE '%"label":"端口号"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"服务类型"', '"label":"Service Type"')
|
||||
WHERE fields LIKE '%"label":"服务类型"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否使用SSL"', '"label":"Use SSL"')
|
||||
WHERE fields LIKE '%"label":"是否使用SSL"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"请求方式"', '"label":"Request Method"')
|
||||
WHERE fields LIKE '%"label":"请求方式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"请求参数"', '"label":"Request Parameters"')
|
||||
WHERE fields LIKE '%"label":"请求参数"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"请求头"', '"label":"Request Headers"')
|
||||
WHERE fields LIKE '%"label":"请求头"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音频格式"', '"label":"Audio Format"')
|
||||
WHERE fields LIKE '%"label":"音频格式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"访问令牌"', '"label":"Access Token"')
|
||||
WHERE fields LIKE '%"label":"访问令牌"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"响应格式"', '"label":"Response Format"')
|
||||
WHERE fields LIKE '%"label":"响应格式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音色"', '"label":"Voice"')
|
||||
WHERE fields LIKE '%"label":"音色"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"应用密钥"', '"label":"App Key"')
|
||||
WHERE fields LIKE '%"label":"应用密钥"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"访问密钥ID"', '"label":"Access Key ID"')
|
||||
WHERE fields LIKE '%"label":"访问密钥ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"访问密钥密码"', '"label":"Access Key Secret"')
|
||||
WHERE fields LIKE '%"label":"访问密钥密码"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"授权"', '"label":"Authorization"')
|
||||
WHERE fields LIKE '%"label":"授权"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"速度"', '"label":"Speed"')
|
||||
WHERE fields LIKE '%"label":"速度"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"温度"', '"label":"Temperature"')
|
||||
WHERE fields LIKE '%"label":"温度"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音色ID"', '"label":"Voice ID"')
|
||||
WHERE fields LIKE '%"label":"音色ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"采样率"', '"label":"Sample Rate"')
|
||||
WHERE fields LIKE '%"label":"采样率"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"参考音频"', '"label":"Reference Audio"')
|
||||
WHERE fields LIKE '%"label":"参考音频"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"参考文本"', '"label":"Reference Text"')
|
||||
WHERE fields LIKE '%"label":"参考文本"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否标准化"', '"label":"Normalize"')
|
||||
WHERE fields LIKE '%"label":"是否标准化"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"最大新令牌数"', '"label":"Max New Tokens"')
|
||||
WHERE fields LIKE '%"label":"最大新令牌数"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"块长度"', '"label":"Chunk Length"')
|
||||
WHERE fields LIKE '%"label":"块长度"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"重复惩罚"', '"label":"Repetition Penalty"')
|
||||
WHERE fields LIKE '%"label":"重复惩罚"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否流式"', '"label":"Streaming"')
|
||||
WHERE fields LIKE '%"label":"是否流式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否使用内存缓存"', '"label":"Use Memory Cache"')
|
||||
WHERE fields LIKE '%"label":"是否使用内存缓存"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"种子"', '"label":"Seed"')
|
||||
WHERE fields LIKE '%"label":"种子"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"通道数"', '"label":"Channels"')
|
||||
WHERE fields LIKE '%"label":"通道数"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"参考ID"', '"label":"Reference ID"')
|
||||
WHERE fields LIKE '%"label":"参考ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"组ID"', '"label":"Group ID"')
|
||||
WHERE fields LIKE '%"label":"组ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"文本语言"', '"label":"Text Language"')
|
||||
WHERE fields LIKE '%"label":"文本语言"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"参考音频路径"', '"label":"Reference Audio Path"')
|
||||
WHERE fields LIKE '%"label":"参考音频路径"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"提示文本"', '"label":"Prompt Text"')
|
||||
WHERE fields LIKE '%"label":"提示文本"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"提示语言"', '"label":"Prompt Language"')
|
||||
WHERE fields LIKE '%"label":"提示语言"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"文本分割方法"', '"label":"Text Split Method"')
|
||||
WHERE fields LIKE '%"label":"文本分割方法"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"批处理大小"', '"label":"Batch Size"')
|
||||
WHERE fields LIKE '%"label":"批处理大小"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"批处理阈值"', '"label":"Batch Threshold"')
|
||||
WHERE fields LIKE '%"label":"批处理阈值"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否分桶"', '"label":"Split Bucket"')
|
||||
WHERE fields LIKE '%"label":"是否分桶"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否返回片段"', '"label":"Return Fragment"')
|
||||
WHERE fields LIKE '%"label":"是否返回片段"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"速度因子"', '"label":"Speed Factor"')
|
||||
WHERE fields LIKE '%"label":"速度因子"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否流式模式"', '"label":"Streaming Mode"')
|
||||
WHERE fields LIKE '%"label":"是否流式模式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否并行推理"', '"label":"Parallel Inference"')
|
||||
WHERE fields LIKE '%"label":"是否并行推理"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"辅助参考音频路径"', '"label":"Auxiliary Reference Audio Paths"')
|
||||
WHERE fields LIKE '%"label":"辅助参考音频路径"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"切分标点"', '"label":"Cut Punctuation"')
|
||||
WHERE fields LIKE '%"label":"切分标点"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"输入参考"', '"label":"Input References"')
|
||||
WHERE fields LIKE '%"label":"输入参考"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"采样步数"', '"label":"Sample Steps"')
|
||||
WHERE fields LIKE '%"label":"采样步数"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"是否使用SR"', '"label":"Use SR"')
|
||||
WHERE fields LIKE '%"label":"是否使用SR"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音调因子"', '"label":"Pitch Factor"')
|
||||
WHERE fields LIKE '%"label":"音调因子"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音量变化"', '"label":"Volume Change dB"')
|
||||
WHERE fields LIKE '%"label":"音量变化"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"目标语言"', '"label":"Target Language"')
|
||||
WHERE fields LIKE '%"label":"目标语言"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"格式"', '"label":"Format"')
|
||||
WHERE fields LIKE '%"label":"格式"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"情感"', '"label":"Emotion"')
|
||||
WHERE fields LIKE '%"label":"情感"%';
|
||||
|
||||
-- Additional field translations
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"应用ID"', '"label":"App ID"')
|
||||
WHERE fields LIKE '%"label":"应用ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"应用AppID"', '"label":"App ID"')
|
||||
WHERE fields LIKE '%"label":"应用AppID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"应用AppKey"', '"label":"App Key"')
|
||||
WHERE fields LIKE '%"label":"应用AppKey"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"临时Token"', '"label":"Temporary Token"')
|
||||
WHERE fields LIKE '%"label":"临时Token"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"AccessKey ID"', '"label":"Access Key ID"')
|
||||
WHERE fields LIKE '%"label":"AccessKey ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"AccessKey Secret"', '"label":"Access Key Secret"')
|
||||
WHERE fields LIKE '%"label":"AccessKey Secret"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"API服务地址"', '"label":"API Service URL"')
|
||||
WHERE fields LIKE '%"label":"API服务地址"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"API地址"', '"label":"API URL"')
|
||||
WHERE fields LIKE '%"label":"API地址"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"WebSocket地址"', '"label":"WebSocket URL"')
|
||||
WHERE fields LIKE '%"label":"WebSocket地址"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"资源ID"', '"label":"Resource ID"')
|
||||
WHERE fields LIKE '%"label":"资源ID"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"默认音色"', '"label":"Default Voice"')
|
||||
WHERE fields LIKE '%"label":"默认音色"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"断句检测时间"', '"label":"Sentence Silence Detection Time"')
|
||||
WHERE fields LIKE '%"label":"断句检测时间"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"集群"', '"label":"Cluster"')
|
||||
WHERE fields LIKE '%"label":"集群"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"热词文件名称"', '"label":"Hotword File Name"')
|
||||
WHERE fields LIKE '%"label":"热词文件名称"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"替换词文件名称"', '"label":"Replacement File Name"')
|
||||
WHERE fields LIKE '%"label":"替换词文件名称"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"区域"', '"label":"Region"')
|
||||
WHERE fields LIKE '%"label":"区域"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"语言参数"', '"label":"Language Parameter"')
|
||||
WHERE fields LIKE '%"label":"语言参数"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音量"', '"label":"Volume"')
|
||||
WHERE fields LIKE '%"label":"音量"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"语速"', '"label":"Speech Rate"')
|
||||
WHERE fields LIKE '%"label":"语速"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"音调"', '"label":"Pitch"')
|
||||
WHERE fields LIKE '%"label":"音调"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"检测阈值"', '"label":"Detection Threshold"')
|
||||
WHERE fields LIKE '%"label":"检测阈值"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"模型目录"', '"label":"Model Directory"')
|
||||
WHERE fields LIKE '%"label":"模型目录"%';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET fields = REPLACE(fields, '"label":"最小静音时长"', '"label":"Min Silence Duration"')
|
||||
WHERE fields LIKE '%"label":"最小静音时长"%';
|
||||
|
||||
-- Update placeholder values in ai_model_config
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的api_key"', '"your_api_key"')
|
||||
WHERE config_json LIKE '%"你的api_key"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的网关访问密钥"', '"your_gateway_access_key"')
|
||||
WHERE config_json LIKE '%"你的网关访问密钥"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的app_id"', '"your_app_id"')
|
||||
WHERE config_json LIKE '%"你的app_id"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的bot_id"', '"your_bot_id"')
|
||||
WHERE config_json LIKE '%"你的bot_id"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的user_id"', '"your_user_id"')
|
||||
WHERE config_json LIKE '%"你的user_id"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的personal_access_token"', '"your_personal_access_token"')
|
||||
WHERE config_json LIKE '%"你的personal_access_token"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的home assistant api访问令牌"', '"your_home_assistant_api_token"')
|
||||
WHERE config_json LIKE '%"你的home assistant api访问令牌"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的Secret ID"', '"your_secret_id"')
|
||||
WHERE config_json LIKE '%"你的Secret ID"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的Secret Key"', '"your_secret_key"')
|
||||
WHERE config_json LIKE '%"你的Secret Key"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的appkey"', '"your_appkey"')
|
||||
WHERE config_json LIKE '%"你的appkey"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的access_key_id"', '"your_access_key_id"')
|
||||
WHERE config_json LIKE '%"你的access_key_id"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的access_key_secret"', '"your_access_key_secret"')
|
||||
WHERE config_json LIKE '%"你的access_key_secret"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的API Key"', '"your_api_key"')
|
||||
WHERE config_json LIKE '%"你的API Key"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的应用ID"', '"your_app_id"')
|
||||
WHERE config_json LIKE '%"你的应用ID"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的音色ID"', '"your_voice_id"')
|
||||
WHERE config_json LIKE '%"你的音色ID"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的访问令牌"', '"your_access_token"')
|
||||
WHERE config_json LIKE '%"你的访问令牌"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的资源ID"', '"your_resource_id"')
|
||||
WHERE config_json LIKE '%"你的资源ID"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的默认音色"', '"your_default_voice"')
|
||||
WHERE config_json LIKE '%"你的默认音色"%';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET config_json = REPLACE(config_json, '"你的集群"', '"your_cluster"')
|
||||
WHERE config_json LIKE '%"你的集群"%';
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
-- Translate model provider names and descriptions from Chinese to English
|
||||
|
||||
-- Update provider names
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'SileroVAD Voice Activity Detection'
|
||||
WHERE name = 'SileroVAD语音活动检测';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'FunASR Speech Recognition'
|
||||
WHERE name = 'FunASR语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'SherpaASR Speech Recognition'
|
||||
WHERE name = 'SherpaASR语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Volcano Engine Speech Recognition'
|
||||
WHERE name = '火山引擎语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Tencent Speech Recognition'
|
||||
WHERE name = '腾讯语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Tencent Speech Synthesis'
|
||||
WHERE name = '腾讯语音合成';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Alibaba Cloud Speech Recognition'
|
||||
WHERE name = '阿里云语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Alibaba Cloud Speech Recognition (Streaming)'
|
||||
WHERE name = '阿里云语音识别(流式)';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Baidu Speech Recognition'
|
||||
WHERE name = '百度语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'OpenAI Speech Recognition'
|
||||
WHERE name = 'OpenAI语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Volcano Engine Speech Recognition (Streaming)'
|
||||
WHERE name = '火山引擎语音识别(流式)';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Alibaba Bailian Interface'
|
||||
WHERE name = '阿里百炼接口';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Volcano Engine LLM'
|
||||
WHERE name = '火山引擎LLM';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Volcano Engine TTS'
|
||||
WHERE name = '火山引擎TTS';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Alibaba Cloud TTS'
|
||||
WHERE name = '阿里云TTS';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Volcano Dual-Stream Speech Synthesis'
|
||||
WHERE name = '火山双流式语音合成';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Linkerai Speech Synthesis'
|
||||
WHERE name = 'Linkerai语音合成';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Alibaba Cloud Speech Synthesis (Streaming)'
|
||||
WHERE name = '阿里云语音合成(流式)';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Index-TTS-vLLM Streaming Speech Synthesis'
|
||||
WHERE name = 'Index-TTS-vLLM流式语音合成';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Mem0AI Memory'
|
||||
WHERE name = 'Mem0AI记忆';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'No Memory'
|
||||
WHERE name = '无记忆';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Local Short Memory'
|
||||
WHERE name = '本地短记忆';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'No Intent Recognition'
|
||||
WHERE name = '无意图识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'LLM Intent Recognition'
|
||||
WHERE name = 'LLM意图识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'Function Call Intent Recognition'
|
||||
WHERE name = '函数调用意图识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'FunASR Server Speech Recognition'
|
||||
WHERE name = 'FunASR服务语音识别';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'MiniMax Speech Synthesis'
|
||||
WHERE name = 'MiniMax语音合成';
|
||||
|
||||
UPDATE ai_model_provider
|
||||
SET name = 'OpenAI Speech Synthesis'
|
||||
WHERE name = 'OpenAI语音合成';
|
||||
|
||||
-- Update model config names
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Zhipu AI'
|
||||
WHERE model_name = '智谱AI';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Tongyi Qianwen'
|
||||
WHERE model_name = '通义千问';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Tongyi Bailian'
|
||||
WHERE model_name = '通义百炼';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Doubao Large Model'
|
||||
WHERE model_name = '豆包大模型';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Google Gemini'
|
||||
WHERE model_name = '谷歌Gemini';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Tencent Speech Recognition'
|
||||
WHERE model_name = '腾讯语音识别';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Alibaba Cloud Speech Recognition'
|
||||
WHERE model_name = '阿里云语音识别';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Baidu Speech Recognition'
|
||||
WHERE model_name = '百度语音识别';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'MiniMax Speech Synthesis'
|
||||
WHERE model_name = 'MiniMax语音合成';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'OpenAI Speech Synthesis'
|
||||
WHERE model_name = 'OpenAI语音合成';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Volcano Dual-Stream Speech Synthesis'
|
||||
WHERE model_name = '火山双流式语音合成';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Linkerai Speech Synthesis'
|
||||
WHERE model_name = 'Linkerai语音合成';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Mem0AI Memory'
|
||||
WHERE model_name = 'Mem0AI记忆';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Function Call Intent Recognition'
|
||||
WHERE model_name = '函数调用意图识别';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Zhipu Visual AI'
|
||||
WHERE model_name = '智谱视觉AI';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Qianwen Visual Model'
|
||||
WHERE model_name = '千问视觉模型';
|
||||
|
||||
UPDATE ai_model_config
|
||||
SET model_name = 'Volcano Edge Large Model Gateway'
|
||||
WHERE model_name = '火山引擎边缘大模型网关';
|
||||
|
||||
-- Update TTS voice names
|
||||
UPDATE ai_tts_voice
|
||||
SET name = 'Alibaba Cloud Xiaoyun'
|
||||
WHERE name = '阿里云小云';
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
-- Translate system parameter remarks from Chinese to English
|
||||
|
||||
UPDATE sys_params
|
||||
SET remark = 'Time to disconnect when no voice input (seconds)'
|
||||
WHERE param_code = 'close_connection_no_voice_time';
|
||||
|
||||
UPDATE sys_params
|
||||
SET remark = 'Wake word list for wake word recognition'
|
||||
WHERE param_code = 'wakeup_words';
|
||||
|
||||
UPDATE sys_params
|
||||
SET remark = 'Home Assistant API key'
|
||||
WHERE param_code = 'plugins.home_assistant.api_key';
|
||||
|
||||
-- Update any Chinese wake words to English equivalents (optional, can be customized by user)
|
||||
UPDATE sys_params
|
||||
SET param_value = 'hello xiaozhi;hey xiaozhi;xiaozhi xiaozhi;hey assistant;hello assistant;wake up;listen to me;hey buddy'
|
||||
WHERE param_code = 'wakeup_words' AND param_value LIKE '%你好小智%';
|
||||
|
||||
-- Translate column comments (if needed for documentation)
|
||||
-- Note: These are database structure changes, not data changes
|
||||
-- ALTER TABLE sys_params MODIFY COLUMN remark VARCHAR(255) COMMENT 'Parameter description';
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
-- Amazon Transcribe Streaming ASR provider and model configuration
|
||||
|
||||
-- Add Amazon Transcribe Streaming real-time ASR provider
|
||||
DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_ASR_AmazonStreamASR';
|
||||
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`)
|
||||
VALUES ('SYSTEM_ASR_AmazonStreamASR', 'ASR', 'amazon_transcribe_realtime', 'Amazon Transcribe Streaming',
|
||||
'[{"key":"aws_access_key_id","label":"AWS Access Key ID","type":"string"},{"key":"aws_secret_access_key","label":"AWS Secret Access Key","type":"string"},{"key":"aws_region","label":"AWS Region","type":"string"},{"key":"language_code","label":"Default Language Code","type":"string"},{"key":"enable_language_detection","label":"Enable Language Detection","type":"boolean"},{"key":"use_multiple_languages","label":"Support Multiple Languages","type":"boolean"},{"key":"romanized_output","label":"Romanized Output","type":"boolean"},{"key":"sample_rate","label":"Sample Rate","type":"number"},{"key":"media_encoding","label":"Media Encoding","type":"string"},{"key":"output_dir","label":"Output Directory","type":"string"},{"key":"timeout","label":"Timeout (seconds)","type":"number"}]',
|
||||
4, 1, NOW(), 1, NOW());
|
||||
|
||||
-- Add Amazon Transcribe Streaming model configuration
|
||||
DELETE FROM `ai_model_config` WHERE id = 'ASR_AmazonStreamASR';
|
||||
INSERT INTO `ai_model_config` VALUES ('ASR_AmazonStreamASR', 'ASR', 'AmazonStreamASR', 'Amazon Transcribe Streaming', 0, 1,
|
||||
'{"type": "amazon_transcribe_realtime", "aws_access_key_id": "", "aws_secret_access_key": "", "aws_region": "us-east-1", "language_code": "en-IN", "enable_language_detection": true, "use_multiple_languages": true, "romanized_output": true, "sample_rate": 16000, "media_encoding": "pcm", "output_dir": "tmp/", "timeout": 30}',
|
||||
'https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html',
|
||||
'Amazon Transcribe Streaming Configuration:
|
||||
1. Real-time speech recognition with fast response (seconds)
|
||||
2. Supports automatic language detection for all major Indian languages
|
||||
3. Supported languages: Hindi, Bengali, Telugu, Tamil, Gujarati, Kannada, Malayalam, Marathi, Punjabi, English (India)
|
||||
4. Can output romanized text for local languages
|
||||
5. Supports speakers switching languages mid-conversation
|
||||
6. Requires AWS credentials and appropriate IAM permissions
|
||||
7. Real-time transcription is better suited for conversation scenarios than batch processing
|
||||
Setup Steps:
|
||||
1. Visit AWS Console: https://console.aws.amazon.com/
|
||||
2. Create IAM user and get access keys: https://console.aws.amazon.com/iam/home#/security_credentials
|
||||
3. Add Amazon Transcribe permissions policy to the user',
|
||||
4, NULL, NULL, NULL, NULL);
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
-- Add GroqLLM Provider
|
||||
DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_LLM_GroqLLM';
|
||||
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
|
||||
('SYSTEM_LLM_GroqLLM', 'LLM', 'groq', 'Groq LLM', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"model_name","label":"Model Name","type":"string"},{"key":"base_url","label":"Base URL","type":"string"},{"key":"temperature","label":"Temperature","type":"number"},{"key":"max_tokens","label":"Max Tokens","type":"number"},{"key":"top_p","label":"Top P","type":"number"},{"key":"frequency_penalty","label":"Frequency Penalty","type":"number"},{"key":"timeout","label":"Timeout (seconds)","type":"number"},{"key":"max_retries","label":"Max Retries","type":"number"},{"key":"retry_delay","label":"Retry Delay (seconds)","type":"number"}]', 15, 1, NOW(), 1, NOW());
|
||||
|
||||
-- Add GroqLLM Model Configuration
|
||||
DELETE FROM `ai_model_config` WHERE id = 'LLM_GroqLLM';
|
||||
INSERT INTO `ai_model_config` VALUES ('LLM_GroqLLM', 'LLM', 'GroqLLM', 'Groq LLM', 0, 1, '{"type": "openai", "api_key": "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", "model_name": "openai/gpt-oss-20b", "base_url": "https://api.groq.com/openai/v1", "temperature": 0.7, "max_tokens": 2048, "top_p": 1.0, "frequency_penalty": 0, "timeout": 15, "max_retries": 2, "retry_delay": 1}', NULL, NULL, 16, NULL, NULL, NULL, NULL);
|
||||
|
||||
-- Update GroqLLM Configuration Documentation
|
||||
UPDATE `ai_model_config` SET
|
||||
`doc_link` = 'https://console.groq.com/',
|
||||
`remark` = 'Groq LLM Configuration Guide:
|
||||
1. Groq is an AI chip company focused on high-performance inference, providing fast LLM inference services
|
||||
2. Supports various open-source large language models like Llama, Mixtral, etc.
|
||||
3. Features ultra-low latency inference performance, suitable for real-time conversation scenarios
|
||||
4. Uses OpenAI-compatible API interface for easy integration
|
||||
5. Requires API key from Groq official website
|
||||
|
||||
Configuration Parameters:
|
||||
- api_key: API key obtained from Groq console
|
||||
- model_name: Model name, e.g., llama3-8b-8192, mixtral-8x7b-32768, etc.
|
||||
- base_url: Groq API endpoint, typically https://api.groq.com/openai/v1
|
||||
- temperature: Controls output randomness (0-2), lower values are more deterministic
|
||||
- max_tokens: Maximum tokens to generate per request
|
||||
- top_p: Nucleus sampling parameter controlling output diversity
|
||||
- frequency_penalty: Frequency penalty to reduce repetitive content
|
||||
- timeout: Request timeout in seconds, recommended 15s (Groq is fast)
|
||||
- max_retries: Maximum retry attempts, recommended 2
|
||||
- retry_delay: Retry interval in seconds, recommended 1s
|
||||
|
||||
Get API Key: https://console.groq.com/keys
|
||||
Model List: https://console.groq.com/docs/models
|
||||
' WHERE `id` = 'LLM_GroqLLM';
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
-- Add play_story plugin support
|
||||
-- This adds play_story to all agents that currently have play_music
|
||||
|
||||
-- 1. Add play_story plugin provider
|
||||
DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY';
|
||||
INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date)
|
||||
VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', 'Story Playback', JSON_ARRAY(), 25, 0, NOW(), 0, NOW());
|
||||
|
||||
-- 2. Add play_story to all agents that have play_music
|
||||
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
|
||||
SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{}'
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'play_music'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ai_agent_plugin_mapping m2
|
||||
JOIN ai_model_provider p2 ON p2.id = m2.plugin_id
|
||||
WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story'
|
||||
);
|
||||
|
||||
-- 3. Add optional configuration fields for play_story
|
||||
UPDATE `ai_model_provider` SET
|
||||
fields = JSON_ARRAY(
|
||||
JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', 'Story Directory', 'default', './stories'),
|
||||
JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', 'Story File Extensions', 'default', '.mp3;.wav;.p3'),
|
||||
JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', 'Refresh Time (seconds)', 'default', '300')
|
||||
)
|
||||
WHERE id = 'SYSTEM_PLUGIN_STORY';
|
||||
|
|
@ -304,6 +304,7 @@ databaseChangeLog:
|
|||
encoding: utf8
|
||||
path: classpath:db/changelog/202508131557.sql
|
||||
- changeSet:
|
||||
|
||||
id: 202508231800
|
||||
author: Claude
|
||||
changes:
|
||||
|
|
@ -324,3 +325,46 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202508291500.sql
|
||||
|
||||
id: 202501230002_translate_dict_names
|
||||
author: cheeko
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202501230002_translate_dict_names.sql
|
||||
- changeSet:
|
||||
id: 202501230003_translate_provider_fields
|
||||
author: cheeko
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202501230003_translate_provider_fields.sql
|
||||
- changeSet:
|
||||
id: 202501230005_translate_sys_params
|
||||
author: cheeko
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202501230005_translate_sys_params.sql
|
||||
- changeSet:
|
||||
id: 202508291530
|
||||
author: claude
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202508291530_add_amazon_transcribe_streaming.sql
|
||||
- changeSet:
|
||||
id: 202508291545
|
||||
author: claude
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202508291545_add_groq_llm.sql
|
||||
- changeSet:
|
||||
id: 202508291600
|
||||
author: claude
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202508291600_add_play_story.sql
|
||||
|
||||
|
|
|
|||
|
|
@ -369,8 +369,8 @@ onMounted(async () => {
|
|||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 底部安全距离 -->
|
||||
<!-- 底部安全距离 -->
|
||||
<!-- Bottom safe area -->
|
||||
<!-- Bottom safe area -->
|
||||
<view style="height: env(safe-area-inset-bottom);" />
|
||||
</view>
|
||||
</view>
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
VUE_APP_TITLE=智控台
|
||||
VUE_APP_TITLE=cheeko
|
||||
|
|
@ -1 +1,2 @@
|
|||
VUE_APP_API_BASE_URL=/xiaozhi
|
||||
VUE_APP_API_BASE_URL=/toy
|
||||
VUE_APP_TITLE=cheeko
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
VUE_APP_API_BASE_URL=/xiaozhi
|
||||
VUE_APP_API_BASE_URL=/toy
|
||||
VUE_APP_PUBLIC_PATH=/
|
||||
# 是否开启CDN
|
||||
VUE_APP_USE_CDN=false
|
||||
VUE_APP_USE_CDN=false
|
||||
VUE_APP_TITLE=cheeko
|
||||
BIN
main/manager-web/public/favicon-16x16.png
Normal file
BIN
main/manager-web/public/favicon-16x16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 724 B |
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 724 B |
|
|
@ -5,7 +5,7 @@
|
|||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||
<link rel="icon" type="image/png" href="<%= BASE_URL %>favicon-16x16.png">
|
||||
<title>
|
||||
<%= process.env.VUE_APP_TITLE %>
|
||||
</title>
|
||||
|
|
|
|||
BIN
main/manager-web/src/assets/favicon-16x16.png
Normal file
BIN
main/manager-web/src/assets/favicon-16x16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 724 B |
|
|
@ -1,5 +1,5 @@
|
|||
<template>
|
||||
<el-dialog :title="'与' + agentName + '的聊天记录' + (currentMacAddress ? '[' + currentMacAddress + ']' : '')"
|
||||
<el-dialog :title="'Chat History with ' + agentName + (currentMacAddress ? ' [' + currentMacAddress + ']' : '')"
|
||||
:visible.sync="dialogVisible" width="80%" :before-close="handleClose" custom-class="chat-history-dialog">
|
||||
<div class="chat-container">
|
||||
<div class="session-list" @scroll="handleScroll">
|
||||
|
|
@ -11,8 +11,8 @@
|
|||
<div class="message-count">{{ session.chatCount > 99 ? '99' : session.chatCount }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="loading" class="loading">加载中...</div>
|
||||
<div v-if="!hasMore" class="no-more">没有更多记录了</div>
|
||||
<div v-if="loading" class="loading">Loading...</div>
|
||||
<div v-if="!hasMore" class="no-more">No more records</div>
|
||||
</div>
|
||||
<div class="chat-content">
|
||||
<div v-if="currentSessionId" class="messages">
|
||||
|
|
@ -32,7 +32,7 @@
|
|||
</div>
|
||||
</div>
|
||||
<div v-else class="no-session-selected">
|
||||
请选择会话查看聊天记录
|
||||
Please select a session to view chat history
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -230,9 +230,9 @@ export default {
|
|||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
|
||||
if (date >= today) {
|
||||
return `今天 ${hours}:${minutes}`;
|
||||
return `Today ${hours}:${minutes}`;
|
||||
} else if (date >= yesterday) {
|
||||
return `昨天 ${hours}:${minutes}`;
|
||||
return `Yesterday ${hours}:${minutes}`;
|
||||
} else {
|
||||
const year = date.getFullYear();
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||
|
|
|
|||
|
|
@ -5,11 +5,11 @@
|
|||
{{ device.agentName }}
|
||||
</div>
|
||||
<div>
|
||||
<img src="@/assets/home/delete.png" alt="" style="width: 18px;height: 18px;margin-right: 10px;"
|
||||
<img src="@/assets/home/delete.png" alt="" class="action-icon delete-icon"
|
||||
@click.stop="handleDelete" />
|
||||
<el-tooltip class="item" effect="dark" :content="device.systemPrompt" placement="top"
|
||||
popper-class="custom-tooltip">
|
||||
<img src="@/assets/home/info.png" alt="" style="width: 18px;height: 18px;" />
|
||||
<img src="@/assets/home/info.png" alt="" class="action-icon info-icon" />
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -141,6 +141,35 @@ export default {
|
|||
color: #999;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.action-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
margin-right: 10px;
|
||||
border-radius: 4px;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.action-icon:hover {
|
||||
transform: scale(1.2);
|
||||
background-color: rgba(87, 120, 255, 0.1);
|
||||
}
|
||||
|
||||
.delete-icon:hover {
|
||||
background-color: rgba(245, 108, 108, 0.1);
|
||||
filter: brightness(1.2);
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.info-icon:hover {
|
||||
background-color: rgba(64, 158, 255, 0.1);
|
||||
filter: brightness(1.2);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@
|
|||
<el-progress v-if="isUploading || uploadStatus === 'success'" :percentage="uploadProgress"
|
||||
:status="uploadStatus"></el-progress>
|
||||
<div class="hint-text">
|
||||
<span>Note: Please upload the original xiaozhi.bin file, not the merged-binary.bin file</span>
|
||||
<span>Note: Please upload the original toy.bin file, not the merged-binary.bin file</span>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="Remarks" prop="remark">
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
class="center-dialog" >
|
||||
<div style="margin: 0 18px; text-align: left; padding: 10px; border-radius: 10px;">
|
||||
<div style="font-size: 30px; color: #3d4566; margin-top: -10px; margin-bottom: 10px; text-align: center;">
|
||||
修改模型
|
||||
Edit Model
|
||||
</div>
|
||||
|
||||
<button class="custom-close-btn" @click="dialogVisible = false">
|
||||
|
|
@ -11,14 +11,14 @@
|
|||
</button>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
|
||||
<div style="font-size: 20px; font-weight: bold; color: #3d4566;">模型信息</div>
|
||||
<div style="font-size: 20px; font-weight: bold; color: #3d4566;">Model Information</div>
|
||||
<div style="display: flex; align-items: center; gap: 20px;">
|
||||
<div style="display: flex; align-items: center;">
|
||||
<span style="margin-right: 8px;">是否启用</span>
|
||||
<span style="margin-right: 8px;">Enable</span>
|
||||
<el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch>
|
||||
</div>
|
||||
<div style="display: none; align-items: center;">
|
||||
<span style="margin-right: 8px;">设为默认</span>
|
||||
<span style="margin-right: 8px;">Set as Default</span>
|
||||
<el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -28,37 +28,37 @@
|
|||
|
||||
<el-form :model="form" ref="form" label-width="100px" label-position="left" class="custom-form">
|
||||
<div style="display: flex; gap: 20px; margin-bottom: 0;">
|
||||
<el-form-item label="模型名称" prop="name" style="flex: 1;">
|
||||
<el-input v-model="form.modelName" placeholder="请输入模型名称" class="custom-input-bg"></el-input>
|
||||
<el-form-item label="Model Name" prop="name" style="flex: 1;">
|
||||
<el-input v-model="form.modelName" placeholder="Enter model name" class="custom-input-bg"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="模型编码" prop="code" style="flex: 1;">
|
||||
<el-input v-model="form.modelCode" placeholder="请输入模型编码" class="custom-input-bg"></el-input>
|
||||
<el-form-item label="Model Code" prop="code" style="flex: 1;">
|
||||
<el-input v-model="form.modelCode" placeholder="Enter model code" class="custom-input-bg"></el-input>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 20px; margin-bottom: 0;">
|
||||
<el-form-item label="供应器" prop="supplier" style="flex: 1;">
|
||||
<el-select v-model="form.configJson.type" placeholder="请选择" class="custom-select custom-input-bg"
|
||||
<el-form-item label="Provider" prop="supplier" style="flex: 1;">
|
||||
<el-select v-model="form.configJson.type" placeholder="Please select" class="custom-select custom-input-bg"
|
||||
style="width: 100%;" @focus="loadProviders" filterable>
|
||||
<el-option v-for="item in providers" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="排序号" prop="sort" style="flex: 1;">
|
||||
<el-input v-model.number="form.sort" type="number" placeholder="请输入排序号" class="custom-input-bg"></el-input>
|
||||
<el-form-item label="Sort Order" prop="sort" style="flex: 1;">
|
||||
<el-input v-model.number="form.sort" type="number" placeholder="Enter sort order" class="custom-input-bg"></el-input>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="文档地址" prop="docUrl" style="margin-bottom: 27px;">
|
||||
<el-input v-model="form.docLink" placeholder="请输入文档地址" class="custom-input-bg"></el-input>
|
||||
<el-form-item label="Doc URL" prop="docUrl" style="margin-bottom: 27px;">
|
||||
<el-input v-model="form.docLink" placeholder="Enter documentation URL" class="custom-input-bg"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="备注" prop="remark" class="prop-remark">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入模型备注" :autosize="{ minRows: 3, maxRows: 5 }"
|
||||
<el-form-item label="Remark" prop="remark" class="prop-remark">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="3" placeholder="Enter model remarks" :autosize="{ minRows: 3, maxRows: 5 }"
|
||||
class="custom-input-bg"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">调用信息</div>
|
||||
<div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">Call Information</div>
|
||||
<div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div>
|
||||
|
||||
<el-form :model="form.configJson" ref="callInfoForm" label-width="auto" class="custom-form">
|
||||
|
|
@ -67,7 +67,7 @@
|
|||
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop"
|
||||
style="flex: 1;">
|
||||
<template v-if="field.type === 'json-textarea'">
|
||||
<el-input v-model="fieldJsonMap[field.prop]" type="textarea" :rows="3" placeholder="请输入JSON格式变量(示例:{'key':'value'})"
|
||||
<el-input v-model="fieldJsonMap[field.prop]" type="textarea" :rows="3" placeholder="Enter JSON format (example: {'key':'value'})"
|
||||
class="custom-input-bg" @change="(val) => handleJsonChange(field.prop, val)"></el-input>
|
||||
</template>
|
||||
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
|
||||
|
|
@ -85,7 +85,7 @@
|
|||
class="save-btn"
|
||||
:loading="saving"
|
||||
:disabled="saving">
|
||||
保存
|
||||
Save
|
||||
</el-button>
|
||||
</div>
|
||||
</el-dialog>
|
||||
|
|
@ -115,7 +115,7 @@ export default {
|
|||
pendingProviderType: null,
|
||||
pendingModelData: null,
|
||||
dynamicCallInfoFields: [],
|
||||
fieldJsonMap: {}, // 用于存储JSON字段的字符串形式
|
||||
fieldJsonMap: {}, // Store string form of JSON fields
|
||||
form: {
|
||||
id: "",
|
||||
modelType: "",
|
||||
|
|
@ -203,9 +203,9 @@ export default {
|
|||
}
|
||||
},
|
||||
handleSave() {
|
||||
this.saving = true; // 开始保存加载
|
||||
this.saving = true; // Start saving loading
|
||||
|
||||
// 处理所有JSON字段
|
||||
// Process all JSON fields
|
||||
Object.keys(this.fieldJsonMap).forEach(key => {
|
||||
const parsed = this.validateJson(this.fieldJsonMap[key]);
|
||||
if (parsed !== null) {
|
||||
|
|
@ -229,11 +229,11 @@ export default {
|
|||
provideCode: this.form.configJson.type,
|
||||
formData,
|
||||
done: () => {
|
||||
this.saving = false; // 保存完成后回调
|
||||
this.saving = false; // Callback after save complete
|
||||
}
|
||||
});
|
||||
|
||||
// 如果父组件不处理done回调,3秒后自动关闭加载状态
|
||||
// If parent component doesn't handle done callback, auto close loading state after 3 seconds
|
||||
setTimeout(() => {
|
||||
this.saving = false;
|
||||
}, 3000);
|
||||
|
|
@ -262,7 +262,7 @@ export default {
|
|||
label: f.label,
|
||||
prop: f.key,
|
||||
type: f.type === 'dict' ? 'json-textarea' : (f.type === 'password' ? 'password' : 'text'),
|
||||
placeholder: `请输入${f.label}`
|
||||
placeholder: `Enter ${f.label}`
|
||||
}));
|
||||
|
||||
if (this.pendingModelData && this.pendingProviderType === providerCode) {
|
||||
|
|
@ -312,13 +312,13 @@ export default {
|
|||
return parsed;
|
||||
}
|
||||
this.$message.error({
|
||||
message: '必须输入字典格式(如 {"key":"value"}),保存则使用原数据',
|
||||
message: 'Must enter dictionary format (e.g. {"key":"value"}), original data will be used if saved',
|
||||
showClose: true
|
||||
});
|
||||
return null;
|
||||
} catch (e) {
|
||||
this.$message.error({
|
||||
message: 'JSON格式错误(如 {"key":"value"}),保存则使用原数据',
|
||||
message: 'JSON format error (e.g. {"key":"value"}), original data will be used if saved',
|
||||
showClose: true
|
||||
});
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ export default new Vuex.Store({
|
|||
userInfo: {}, // 添加用户信息存储
|
||||
isSuperAdmin: false, // 添加superAdmin状态
|
||||
pubConfig: { // 添加公共配置存储
|
||||
version: '',
|
||||
version: '0.7.5',
|
||||
name: 'cheeko-server',
|
||||
year: '©2025',
|
||||
beianIcpNum: 'null',
|
||||
beianGaNum: 'null',
|
||||
allowUserRegister: false
|
||||
|
|
@ -50,7 +52,14 @@ export default new Vuex.Store({
|
|||
localStorage.setItem('isSuperAdmin', isSuperAdmin)
|
||||
},
|
||||
setPubConfig(state, config) {
|
||||
state.pubConfig = config
|
||||
state.pubConfig = {
|
||||
version: config.version || '0.7.5',
|
||||
name: config.name || 'cheeko-server',
|
||||
year: config.year || '©2025',
|
||||
beianIcpNum: config.beianIcpNum || 'null',
|
||||
beianGaNum: config.beianGaNum || 'null',
|
||||
allowUserRegister: config.allowUserRegister || false
|
||||
}
|
||||
},
|
||||
clearAuth(state) {
|
||||
state.token = ''
|
||||
|
|
|
|||
|
|
@ -15,10 +15,10 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主体内容 -->
|
||||
<!-- Main Content -->
|
||||
<div class="main-wrapper">
|
||||
<div class="content-panel">
|
||||
<!-- 左侧字典类型列表 -->
|
||||
<!-- Left side dictionary type list -->
|
||||
<div class="dict-type-panel">
|
||||
<div class="dict-type-header">
|
||||
<el-button type="success" size="mini" @click="showAddDictTypeDialog">Add Dictionary Type</el-button>
|
||||
|
|
@ -42,7 +42,7 @@
|
|||
</el-table>
|
||||
</div>
|
||||
|
||||
<!-- 右侧字典数据列表 -->
|
||||
<!-- Right side dictionary data list -->
|
||||
<div class="content-area">
|
||||
<el-card class="dict-data-card" shadow="never">
|
||||
<el-table ref="dictDataTable" :data="dictDataList" style="width: 100%"
|
||||
|
|
@ -111,11 +111,11 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 使用字典类型编辑弹框组件 -->
|
||||
<!-- Dictionary type edit dialog component -->
|
||||
<DictTypeDialog :visible.sync="dictTypeDialogVisible" :title="dictTypeDialogTitle" :dictTypeData="dictTypeForm"
|
||||
@save="saveDictType" />
|
||||
|
||||
<!-- 使用字典数据编辑弹框组件 -->
|
||||
<!-- Dictionary data edit dialog component -->
|
||||
<DictDataDialog :visible.sync="dictDataDialogVisible" :title="dictDataDialogTitle" :dictData="dictDataForm"
|
||||
:dictTypeId="selectedDictType?.id" @save="saveDictData" />
|
||||
<el-footer style="flex-shrink:unset;">
|
||||
|
|
@ -140,11 +140,11 @@ export default {
|
|||
},
|
||||
data() {
|
||||
return {
|
||||
// 字典类型相关
|
||||
// Dictionary type related
|
||||
dictTypeList: [],
|
||||
dictTypeLoading: false,
|
||||
selectedDictType: null,
|
||||
selectedDictTypes: [], // 恢复多选数组
|
||||
selectedDictTypes: [], // Restore multi-select array
|
||||
dictTypeDialogVisible: false,
|
||||
dictTypeDialogTitle: 'Add Dictionary Type',
|
||||
dictTypeForm: {
|
||||
|
|
@ -153,7 +153,7 @@ export default {
|
|||
dictType: ''
|
||||
},
|
||||
|
||||
// 字典数据相关
|
||||
// Dictionary data related
|
||||
dictDataList: [],
|
||||
dictDataLoading: false,
|
||||
isAllDictDataSelected: false,
|
||||
|
|
@ -167,7 +167,7 @@ export default {
|
|||
sort: 0
|
||||
},
|
||||
search: '',
|
||||
// 添加分页相关数据
|
||||
// Add pagination related data
|
||||
pageSizeOptions: [10, 20, 50, 100],
|
||||
currentPage: 1,
|
||||
pageSize: 10,
|
||||
|
|
@ -178,7 +178,7 @@ export default {
|
|||
this.loadDictTypeList()
|
||||
},
|
||||
methods: {
|
||||
// 字典类型相关方法
|
||||
// Dictionary type related methods
|
||||
loadDictTypeList() {
|
||||
this.dictTypeLoading = true
|
||||
dictApi.getDictTypeList({
|
||||
|
|
@ -255,7 +255,7 @@ export default {
|
|||
})
|
||||
},
|
||||
|
||||
// 字典数据相关方法
|
||||
// Dictionary data related methods
|
||||
loadDictDataList(dictTypeId) {
|
||||
if (!dictTypeId) return
|
||||
this.dictDataLoading = true
|
||||
|
|
@ -273,7 +273,7 @@ export default {
|
|||
}))
|
||||
this.total = data.data.total
|
||||
} else {
|
||||
this.$message.error(data.msg || '获取字典数据失败')
|
||||
this.$message.error(data.msg || 'Failed to get dictionary data')
|
||||
}
|
||||
this.dictDataLoading = false
|
||||
})
|
||||
|
|
@ -286,7 +286,7 @@ export default {
|
|||
},
|
||||
showAddDictDataDialog() {
|
||||
if (!this.selectedDictType) {
|
||||
this.$message.warning('请先选择字典类型')
|
||||
this.$message.warning('Please select a dictionary type first')
|
||||
return
|
||||
}
|
||||
this.dictDataDialogTitle = 'Add Dictionary Data'
|
||||
|
|
@ -351,13 +351,13 @@ export default {
|
|||
},
|
||||
handleSearch() {
|
||||
if (!this.selectedDictType) {
|
||||
this.$message.warning('请先选择字典类型')
|
||||
this.$message.warning('Please select a dictionary type first')
|
||||
return
|
||||
}
|
||||
this.currentPage = 1
|
||||
this.loadDictDataList(this.selectedDictType.id)
|
||||
},
|
||||
// 添加分页相关方法
|
||||
// Add pagination related methods
|
||||
handlePageSizeChange(val) {
|
||||
this.pageSize = val;
|
||||
this.currentPage = 1;
|
||||
|
|
|
|||
|
|
@ -150,23 +150,23 @@ export default {
|
|||
this.isLoading = false;
|
||||
});
|
||||
},
|
||||
// 删除智能体
|
||||
// Delete agent
|
||||
handleDeleteAgent(agentId) {
|
||||
this.$confirm('确定要删除该智能体吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
this.$confirm('Are you sure you want to delete this agent?', 'Confirm', {
|
||||
confirmButtonText: 'Confirm',
|
||||
cancelButtonText: 'Cancel',
|
||||
type: 'warning'
|
||||
}).then(() => {
|
||||
Api.agent.deleteAgent(agentId, (res) => {
|
||||
if (res.data.code === 0) {
|
||||
this.$message.success({
|
||||
message: '删除成功',
|
||||
message: 'Deleted successfully',
|
||||
showClose: true
|
||||
});
|
||||
this.fetchAgentList(); // 刷新列表
|
||||
this.fetchAgentList(); // Refresh list
|
||||
} else {
|
||||
this.$message.error({
|
||||
message: res.data.msg || '删除失败',
|
||||
message: res.data.msg || 'Failed to delete',
|
||||
showClose: true
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,12 +3,12 @@
|
|||
<el-container style="height: 100%;">
|
||||
<el-header>
|
||||
<div style="display: flex;align-items: center;margin-top: 15px;margin-left: 10px;gap: 10px;">
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.svg" style="width: 45px;height: 45px;" />
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" />
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.svg" style="width: 65px;height: 65px;" />
|
||||
<!-- <img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" /> -->
|
||||
</div>
|
||||
</el-header>
|
||||
<div class="login-person">
|
||||
<img loading="lazy" alt="" src="@/assets/login/login-person.png" style="width: 100%;" />
|
||||
<!-- <img loading="lazy" alt="" src="@/assets/login/login-person.png" style="width: 100%;" /> -->
|
||||
</div>
|
||||
<el-main style="position: relative;">
|
||||
<div class="login-box" @keyup.enter="login">
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
<template>
|
||||
<div class="welcome" @keyup.enter="register">
|
||||
<el-container style="height: 100%;">
|
||||
<!-- 保持相同的头部 -->
|
||||
<!-- Keep the same header -->
|
||||
<el-header>
|
||||
<div style="display: flex;align-items: center;margin-top: 15px;margin-left: 10px;gap: 10px;">
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.svg" style="width: 45px;height: 45px;" />
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" />
|
||||
<!-- <img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" /> -->
|
||||
</div>
|
||||
</el-header>
|
||||
<div class="login-person">
|
||||
|
|
@ -13,10 +13,10 @@
|
|||
</div>
|
||||
<el-main style="position: relative;">
|
||||
<div class="login-box">
|
||||
<!-- 修改标题部分 -->
|
||||
<!-- Title section -->
|
||||
<div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;">
|
||||
<img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" />
|
||||
<div class="login-text">注册</div>
|
||||
<div class="login-text">Register</div>
|
||||
<div class="login-welcome">
|
||||
WELCOME TO REGISTER
|
||||
</div>
|
||||
|
|
@ -24,13 +24,13 @@
|
|||
|
||||
<div style="padding: 0 30px;">
|
||||
<form @submit.prevent="register">
|
||||
<!-- 用户名/手机号输入框 -->
|
||||
<!-- Username/phone input box -->
|
||||
<div class="input-box" v-if="!enableMobileRegister">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/username.png" />
|
||||
<el-input v-model="form.username" placeholder="请输入用户名" />
|
||||
<el-input v-model="form.username" placeholder="Enter username" />
|
||||
</div>
|
||||
|
||||
<!-- 手机号注册部分 -->
|
||||
<!-- Mobile registration section -->
|
||||
<template v-if="enableMobileRegister">
|
||||
<div class="input-box">
|
||||
<div style="display: flex; align-items: center; width: 100%;">
|
||||
|
|
@ -38,79 +38,79 @@
|
|||
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
|
||||
:value="item.key" />
|
||||
</el-select>
|
||||
<el-input v-model="form.mobile" placeholder="请输入手机号码" />
|
||||
<el-input v-model="form.mobile" placeholder="Enter phone number" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
|
||||
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
|
||||
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" />
|
||||
<el-input v-model="form.captcha" placeholder="Enter verification code" style="flex: 1;" />
|
||||
</div>
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码"
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Captcha"
|
||||
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
|
||||
</div>
|
||||
|
||||
<!-- 手机验证码 -->
|
||||
<!-- Mobile verification code -->
|
||||
|
||||
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
|
||||
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" />
|
||||
<el-input v-model="form.mobileCaptcha" placeholder="请输入手机验证码" style="flex: 1;" maxlength="6" />
|
||||
<el-input v-model="form.mobileCaptcha" placeholder="Enter SMS code" style="flex: 1;" maxlength="6" />
|
||||
</div>
|
||||
<el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha"
|
||||
@click="sendMobileCaptcha">
|
||||
<span>
|
||||
{{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
|
||||
{{ countdown > 0 ? `Retry in ${countdown}s` : 'Send Code' }}
|
||||
</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 密码输入框 -->
|
||||
<!-- Password input box -->
|
||||
<div class="input-box">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
|
||||
<el-input v-model="form.password" placeholder="请输入密码" type="password" show-password />
|
||||
<el-input v-model="form.password" placeholder="Enter password" type="password" show-password />
|
||||
</div>
|
||||
|
||||
<!-- 新增确认密码 -->
|
||||
<!-- Confirm password -->
|
||||
<div class="input-box">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
|
||||
<el-input v-model="form.confirmPassword" placeholder="请确认密码" type="password" show-password />
|
||||
<el-input v-model="form.confirmPassword" placeholder="Confirm password" type="password" show-password />
|
||||
</div>
|
||||
|
||||
<!-- 验证码部分保持相同 -->
|
||||
<!-- Captcha section -->
|
||||
<div v-if="!enableMobileRegister"
|
||||
style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
|
||||
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
|
||||
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" />
|
||||
<el-input v-model="form.captcha" placeholder="Enter verification code" style="flex: 1;" />
|
||||
</div>
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码"
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Captcha"
|
||||
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
|
||||
</div>
|
||||
|
||||
<!-- 修改底部链接 -->
|
||||
<!-- Bottom link -->
|
||||
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;">
|
||||
<div style="cursor: pointer;" @click="goToLogin">已有账号?立即登录</div>
|
||||
<div style="cursor: pointer;" @click="goToLogin">Already have an account? Login now</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- 修改按钮文本 -->
|
||||
<div class="login-btn" @click="register">立即注册</div>
|
||||
<!-- Button text -->
|
||||
<div class="login-btn" @click="register">Register Now</div>
|
||||
|
||||
<!-- 保持相同的协议声明 -->
|
||||
<!-- Agreement declaration -->
|
||||
<div style="font-size: 14px;color: #979db1;">
|
||||
注册即同意
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《用户协议》</div>
|
||||
和
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《隐私政策》</div>
|
||||
By registering, you agree to the
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">Terms of Service</div>
|
||||
and
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">Privacy Policy</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-main>
|
||||
|
||||
<!-- 保持相同的页脚 -->
|
||||
<!-- Footer -->
|
||||
<el-footer>
|
||||
<version-footer />
|
||||
</el-footer>
|
||||
|
|
@ -159,7 +159,7 @@ export default {
|
|||
mounted() {
|
||||
this.$store.dispatch('fetchPubConfig').then(() => {
|
||||
if (!this.allowUserRegister) {
|
||||
showDanger('当前不允许普通用户注册');
|
||||
showDanger('User registration is currently not allowed');
|
||||
setTimeout(() => {
|
||||
goToPage('/login');
|
||||
}, 1500);
|
||||
|
|
@ -168,7 +168,7 @@ export default {
|
|||
this.fetchCaptcha();
|
||||
},
|
||||
methods: {
|
||||
// 复用验证码获取方法
|
||||
// Reuse captcha fetch method
|
||||
fetchCaptcha() {
|
||||
this.form.captchaId = getUUID();
|
||||
Api.user.getCaptcha(this.form.captchaId, (res) => {
|
||||
|
|
@ -177,13 +177,13 @@ export default {
|
|||
this.captchaUrl = URL.createObjectURL(blob);
|
||||
|
||||
} else {
|
||||
console.error('验证码加载异常:', error);
|
||||
showDanger('验证码加载失败,点击刷新');
|
||||
console.error('Captcha loading error:', error);
|
||||
showDanger('Failed to load captcha, click to refresh');
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
// 封装输入验证逻辑
|
||||
// Encapsulate input validation logic
|
||||
validateInput(input, message) {
|
||||
if (!input.trim()) {
|
||||
showDanger(message);
|
||||
|
|
@ -192,26 +192,26 @@ export default {
|
|||
return true;
|
||||
},
|
||||
|
||||
// 发送手机验证码
|
||||
// Send mobile verification code
|
||||
sendMobileCaptcha() {
|
||||
if (!validateMobile(this.form.mobile, this.form.areaCode)) {
|
||||
showDanger('请输入正确的手机号码');
|
||||
showDanger('Please enter a valid phone number');
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证图形验证码
|
||||
if (!this.validateInput(this.form.captcha, '请输入图形验证码')) {
|
||||
// Verify captcha
|
||||
if (!this.validateInput(this.form.captcha, 'Please enter the captcha')) {
|
||||
this.fetchCaptcha();
|
||||
return;
|
||||
}
|
||||
|
||||
// 清除可能存在的旧定时器
|
||||
// Clear any existing timer
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
// 开始倒计时
|
||||
// Start countdown
|
||||
this.countdown = 60;
|
||||
this.timer = setInterval(() => {
|
||||
if (this.countdown > 0) {
|
||||
|
|
@ -222,49 +222,49 @@ export default {
|
|||
}
|
||||
}, 1000);
|
||||
|
||||
// 调用发送验证码接口
|
||||
// Call send verification code API
|
||||
Api.user.sendSmsVerification({
|
||||
phone: this.form.areaCode + this.form.mobile,
|
||||
captcha: this.form.captcha,
|
||||
captchaId: this.form.captchaId
|
||||
}, (res) => {
|
||||
showSuccess('验证码发送成功');
|
||||
showSuccess('Verification code sent successfully');
|
||||
}, (err) => {
|
||||
showDanger(err.data.msg || '验证码发送失败');
|
||||
showDanger(err.data.msg || 'Failed to send verification code');
|
||||
this.countdown = 0;
|
||||
this.fetchCaptcha();
|
||||
});
|
||||
},
|
||||
|
||||
// 注册逻辑
|
||||
// Registration logic
|
||||
register() {
|
||||
if (this.enableMobileRegister) {
|
||||
// 手机号注册验证
|
||||
// Mobile registration validation
|
||||
if (!validateMobile(this.form.mobile, this.form.areaCode)) {
|
||||
showDanger('请输入正确的手机号码');
|
||||
showDanger('Please enter a valid phone number');
|
||||
return;
|
||||
}
|
||||
if (!this.form.mobileCaptcha) {
|
||||
showDanger('请输入手机验证码');
|
||||
showDanger('Please enter the SMS verification code');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// 用户名注册验证
|
||||
if (!this.validateInput(this.form.username, '用户名不能为空')) {
|
||||
// Username registration validation
|
||||
if (!this.validateInput(this.form.username, 'Username cannot be empty')) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if (!this.validateInput(this.form.password, '密码不能为空')) {
|
||||
// Validate password
|
||||
if (!this.validateInput(this.form.password, 'Password cannot be empty')) {
|
||||
return;
|
||||
}
|
||||
if (this.form.password !== this.form.confirmPassword) {
|
||||
showDanger('两次输入的密码不一致')
|
||||
showDanger('Passwords do not match')
|
||||
return
|
||||
}
|
||||
// 验证验证码
|
||||
if (!this.validateInput(this.form.captcha, '验证码不能为空')) {
|
||||
// Validate captcha
|
||||
if (!this.validateInput(this.form.captcha, 'Verification code cannot be empty')) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -273,11 +273,11 @@ export default {
|
|||
}
|
||||
|
||||
Api.user.register(this.form, ({ data }) => {
|
||||
showSuccess('注册成功!')
|
||||
showSuccess('Registration successful!')
|
||||
goToPage('/login')
|
||||
}, (err) => {
|
||||
showDanger(err.data.msg || '注册失败')
|
||||
if (err.data != null && err.data.msg != null && err.data.msg.indexOf('图形验证码') > -1) {
|
||||
showDanger(err.data.msg || 'Registration failed')
|
||||
if (err.data != null && err.data.msg != null && (err.data.msg.indexOf('captcha') > -1 || err.data.msg.indexOf('图形验证码') > -1)) {
|
||||
this.fetchCaptcha()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
<template>
|
||||
<div class="welcome" @keyup.enter="retrievePassword">
|
||||
<el-container style="height: 100%;">
|
||||
<!-- 保持相同的头部 -->
|
||||
<!-- Keep the same header -->
|
||||
<el-header>
|
||||
<div style="display: flex;align-items: center;margin-top: 15px;margin-left: 10px;gap: 10px;">
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.svg" style="width: 45px;height: 45px;" />
|
||||
<img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" />
|
||||
<!-- <img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" style="height: 18px;" /> -->
|
||||
</div>
|
||||
</el-header>
|
||||
<div class="login-person">
|
||||
|
|
@ -14,83 +14,83 @@
|
|||
<el-main style="position: relative;">
|
||||
<form @submit.prevent="retrievePassword">
|
||||
<div class="login-box">
|
||||
<!-- 修改标题部分 -->
|
||||
<!-- Title section -->
|
||||
<div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;">
|
||||
<img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" />
|
||||
<div class="login-text">重置密码</div>
|
||||
<div class="login-text">Reset Password</div>
|
||||
<div class="login-welcome">
|
||||
PASSWORD RETRIEVE
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="padding: 0 30px;">
|
||||
<!-- 手机号输入 -->
|
||||
<!-- Phone number input -->
|
||||
<div class="input-box">
|
||||
<div style="display: flex; align-items: center; width: 100%;">
|
||||
<el-select v-model="form.areaCode" style="width: 220px; margin-right: 10px;">
|
||||
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
|
||||
:value="item.key" />
|
||||
</el-select>
|
||||
<el-input v-model="form.mobile" placeholder="请输入手机号码" />
|
||||
<el-input v-model="form.mobile" placeholder="Enter phone number" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
|
||||
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
|
||||
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" />
|
||||
<el-input v-model="form.captcha" placeholder="Enter verification code" style="flex: 1;" />
|
||||
</div>
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码"
|
||||
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Captcha"
|
||||
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
|
||||
</div>
|
||||
|
||||
<!-- 手机验证码 -->
|
||||
<!-- Mobile verification code -->
|
||||
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
|
||||
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" />
|
||||
<el-input v-model="form.mobileCaptcha" placeholder="请输入手机验证码" style="flex: 1;" maxlength="6" />
|
||||
<el-input v-model="form.mobileCaptcha" placeholder="Enter SMS code" style="flex: 1;" maxlength="6" />
|
||||
</div>
|
||||
<el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha"
|
||||
@click="sendMobileCaptcha">
|
||||
<span>
|
||||
{{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
|
||||
{{ countdown > 0 ? `Retry in ${countdown}s` : 'Send Code' }}
|
||||
</span>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 新密码 -->
|
||||
<!-- New password -->
|
||||
<div class="input-box">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
|
||||
<el-input v-model="form.newPassword" placeholder="请输入新密码" type="password" show-password />
|
||||
<el-input v-model="form.newPassword" placeholder="Enter new password" type="password" show-password />
|
||||
</div>
|
||||
|
||||
<!-- 确认新密码 -->
|
||||
<!-- Confirm new password -->
|
||||
<div class="input-box">
|
||||
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
|
||||
<el-input v-model="form.confirmPassword" placeholder="请确认新密码" type="password" show-password />
|
||||
<el-input v-model="form.confirmPassword" placeholder="Confirm new password" type="password" show-password />
|
||||
</div>
|
||||
|
||||
<!-- 修改底部链接 -->
|
||||
<!-- Bottom link -->
|
||||
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;">
|
||||
<div style="cursor: pointer;" @click="goToLogin">返回登录</div>
|
||||
<div style="cursor: pointer;" @click="goToLogin">Back to Login</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改按钮文本 -->
|
||||
<div class="login-btn" @click="retrievePassword">立即修改</div>
|
||||
<!-- Button text -->
|
||||
<div class="login-btn" @click="retrievePassword">Reset Now</div>
|
||||
|
||||
<!-- 保持相同的协议声明 -->
|
||||
<!-- Agreement declaration -->
|
||||
<div style="font-size: 14px;color: #979db1;">
|
||||
同意
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《用户协议》</div>
|
||||
和
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《隐私政策》</div>
|
||||
By continuing, you agree to the
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">Terms of Service</div>
|
||||
and
|
||||
<div style="display: inline-block;color: #5778FF;cursor: pointer;">Privacy Policy</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</el-main>
|
||||
|
||||
<!-- 保持相同的页脚 -->
|
||||
<!-- Footer -->
|
||||
<el-footer>
|
||||
<version-footer />
|
||||
</el-footer>
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@
|
|||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<el-form-item v-for="(model, index) in models.slice(2)" :key="`model-${index}`" :label="model.label"
|
||||
<el-form-item v-for="(model, index) in models.slice(2).filter(m => m.type !== 'VLLM')" :key="`model-${index}`" :label="model.label"
|
||||
class="model-item">
|
||||
<div class="model-select-wrapper">
|
||||
<el-select v-model="form.model[model.key]" filterable placeholder="Please select" class="form-select"
|
||||
|
|
@ -374,15 +374,15 @@ export default {
|
|||
this.selectedTemplate = template; // Track selected template
|
||||
this.applyTemplateData(template);
|
||||
this.$message.success({
|
||||
message: `「${template.agentName}」模板已应用`,
|
||||
message: `"${template.agentName}" template applied`,
|
||||
showClose: true
|
||||
});
|
||||
} catch (error) {
|
||||
this.$message.error({
|
||||
message: '应用模板失败',
|
||||
message: 'Failed to apply template',
|
||||
showClose: true
|
||||
});
|
||||
console.error('应用模板失败:', error);
|
||||
console.error('Failed to apply template:', error);
|
||||
} finally {
|
||||
this.loadingTemplate = false;
|
||||
}
|
||||
|
|
@ -785,16 +785,18 @@ export default {
|
|||
|
||||
.template-item {
|
||||
height: 4vh;
|
||||
width: 76px;
|
||||
width: auto;
|
||||
border-radius: 8px;
|
||||
background: #e6ebff;
|
||||
background: hsl(228, 100%, 95%);
|
||||
line-height: 4vh;
|
||||
font-weight: 400;
|
||||
font-size: 11px;
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
color: #5778ff;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s ease;
|
||||
padding-left: 10px;
|
||||
padding-right: 10px;
|
||||
}
|
||||
|
||||
.template-item:hover {
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ module.exports = defineConfig({
|
|||
devServer: {
|
||||
port: 8001, // 指定端口为 8001
|
||||
proxy: {
|
||||
'/xiaozhi': {
|
||||
'/toy': {
|
||||
target: 'http://127.0.0.1:8002',
|
||||
changeOrigin: true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
{
|
||||
"production": {
|
||||
"chat_servers": [
|
||||
"ws://192.168.68.66:8000/xiaozhi/v1/"
|
||||
"ws://192.168.68.66:8000/toy/v1/"
|
||||
]
|
||||
},
|
||||
"development": {
|
||||
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
|
||||
"chat_servers": ["ws://192.168.68.66:8000/toy/v1/"],
|
||||
"mac_addresss": ["d8:43:ae:3e:4b:5a"]
|
||||
},
|
||||
"debug": false
|
||||
|
|
|
|||
217
main/xiaozhi-server/add_indian_news_provider.py
Normal file
217
main/xiaozhi-server/add_indian_news_provider.py
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Add get_indian_news_api provider and map it to agents
|
||||
"""
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Connected to database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Connection error: {e}")
|
||||
return None
|
||||
|
||||
def check_existing_news_providers(connection):
|
||||
"""Check what news providers exist"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("=== EXISTING NEWS PROVIDERS ===")
|
||||
cursor.execute("""
|
||||
SELECT id, provider_code, name
|
||||
FROM ai_model_provider
|
||||
WHERE provider_code LIKE '%news%' OR name LIKE '%news%' OR name LIKE '%News%'
|
||||
ORDER BY provider_code
|
||||
""")
|
||||
|
||||
providers = cursor.fetchall()
|
||||
|
||||
if providers:
|
||||
for provider in providers:
|
||||
print(f" {provider[0]} -> {provider[1]} ({provider[2]})")
|
||||
else:
|
||||
print(" No news providers found")
|
||||
|
||||
cursor.close()
|
||||
return providers
|
||||
|
||||
def add_indian_news_provider(connection):
|
||||
"""Add the get_indian_news_api provider"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== ADDING get_indian_news_api PROVIDER ===")
|
||||
|
||||
# Check if it already exists
|
||||
cursor.execute("""
|
||||
SELECT id FROM ai_model_provider WHERE provider_code = 'get_indian_news_api'
|
||||
""")
|
||||
|
||||
if cursor.fetchone():
|
||||
print("[INFO] get_indian_news_api provider already exists!")
|
||||
cursor.close()
|
||||
return True
|
||||
|
||||
try:
|
||||
# Add the provider
|
||||
cursor.execute("""
|
||||
INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date)
|
||||
VALUES ('SYSTEM_PLUGIN_INDIAN_NEWS', 'Plugin', 'get_indian_news_api', 'Indian News API', JSON_ARRAY(), 35, 0, NOW(), 0, NOW())
|
||||
""")
|
||||
|
||||
connection.commit()
|
||||
print("[SUCCESS] Added get_indian_news_api provider!")
|
||||
cursor.close()
|
||||
return True
|
||||
|
||||
except Error as e:
|
||||
print(f"[ERROR] Failed to add provider: {e}")
|
||||
connection.rollback()
|
||||
cursor.close()
|
||||
return False
|
||||
|
||||
def add_to_agents_with_news(connection):
|
||||
"""Add get_indian_news_api to all agents that have other news plugins"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== ADDING TO AGENTS ===")
|
||||
|
||||
# Find agents that have news plugins but not indian news
|
||||
cursor.execute("""
|
||||
SELECT DISTINCT a.id, a.agent_name
|
||||
FROM ai_agent a
|
||||
JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'get_news_from_newsnow'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ai_agent_plugin_mapping m2
|
||||
JOIN ai_model_provider p2 ON p2.id = m2.plugin_id
|
||||
WHERE m2.agent_id = a.id AND p2.provider_code = 'get_indian_news_api'
|
||||
)
|
||||
""")
|
||||
|
||||
agents = cursor.fetchall()
|
||||
|
||||
if not agents:
|
||||
print("[INFO] No agents need get_indian_news_api added")
|
||||
cursor.close()
|
||||
return
|
||||
|
||||
print(f"Adding get_indian_news_api to {len(agents)} agents:")
|
||||
|
||||
added_count = 0
|
||||
for agent_id, agent_name in agents:
|
||||
try:
|
||||
cursor.execute("""
|
||||
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
|
||||
VALUES (%s, 'SYSTEM_PLUGIN_INDIAN_NEWS', '{}')
|
||||
""", (agent_id,))
|
||||
|
||||
print(f" - {agent_name} ({agent_id})")
|
||||
added_count += 1
|
||||
|
||||
except Error as e:
|
||||
print(f" - ERROR adding to {agent_name}: {e}")
|
||||
|
||||
if added_count > 0:
|
||||
try:
|
||||
connection.commit()
|
||||
print(f"\n[SUCCESS] Added get_indian_news_api to {added_count} agents!")
|
||||
except Error as e:
|
||||
connection.rollback()
|
||||
print(f"\n[ERROR] Failed to commit: {e}")
|
||||
return False
|
||||
|
||||
cursor.close()
|
||||
return True
|
||||
|
||||
def verify_complete_setup(connection):
|
||||
"""Verify that all expected functions are now available"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== FINAL VERIFICATION ===")
|
||||
|
||||
# Check a Cheeko agent
|
||||
cursor.execute("SELECT id, agent_name FROM ai_agent WHERE agent_name LIKE '%Cheeko%' LIMIT 1")
|
||||
agent = cursor.fetchone()
|
||||
|
||||
if agent:
|
||||
agent_id, agent_name = agent
|
||||
print(f"Checking agent: {agent_name}")
|
||||
|
||||
cursor.execute("""
|
||||
SELECT p.provider_code
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE m.agent_id = %s AND p.model_type = 'Plugin'
|
||||
ORDER BY p.provider_code
|
||||
""", (agent_id,))
|
||||
|
||||
plugins = cursor.fetchall()
|
||||
available_functions = [plugin[0] for plugin in plugins]
|
||||
|
||||
expected = ['play_music', 'play_story', 'get_weather', 'get_indian_news_api', 'get_news_from_newsnow']
|
||||
|
||||
print(f"Available functions: {available_functions}")
|
||||
print(f"\nFunction Status:")
|
||||
all_present = True
|
||||
for func in expected:
|
||||
status = "[OK]" if func in available_functions else "[MISSING]"
|
||||
print(f" {func}: {status}")
|
||||
if func not in available_functions:
|
||||
all_present = False
|
||||
|
||||
if all_present:
|
||||
print(f"\n[COMPLETE] All expected functions are now available!")
|
||||
print("The agent should now work with manager-api config just like local config")
|
||||
else:
|
||||
print(f"\n[WARNING] Some functions are still missing")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# 1. Check existing news providers
|
||||
existing = check_existing_news_providers(connection)
|
||||
|
||||
# 2. Add the missing provider
|
||||
if add_indian_news_provider(connection):
|
||||
# 3. Add to agents
|
||||
add_to_agents_with_news(connection)
|
||||
|
||||
# 4. Final verification
|
||||
verify_complete_setup(connection)
|
||||
|
||||
print(f"\n[FINAL RESULT]")
|
||||
print("✅ get_indian_news_api provider added")
|
||||
print("✅ Plugin mapped to agents with news functionality")
|
||||
print("✅ All expected functions should now work with manager-api")
|
||||
print("\nNext steps:")
|
||||
print("1. Restart manager-api")
|
||||
print("2. Test both play_story and get_indian_news_api functionality")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
195
main/xiaozhi-server/add_missing_indian_news.py
Normal file
195
main/xiaozhi-server/add_missing_indian_news.py
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Add missing get_indian_news_api plugin to all agents that have other news/weather plugins
|
||||
"""
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Connected to database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Connection error: {e}")
|
||||
return None
|
||||
|
||||
def check_indian_news_provider(connection):
|
||||
"""Check if get_indian_news_api provider exists"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("""
|
||||
SELECT id, provider_code, name
|
||||
FROM ai_model_provider
|
||||
WHERE provider_code = 'get_indian_news_api' OR provider_code LIKE '%indian_news%'
|
||||
""")
|
||||
|
||||
providers = cursor.fetchall()
|
||||
cursor.close()
|
||||
|
||||
if providers:
|
||||
print(f"Found Indian news providers:")
|
||||
for provider in providers:
|
||||
print(f" {provider[0]} -> {provider[1]} ({provider[2]})")
|
||||
return providers[0][0] # Return the ID of the first matching provider
|
||||
else:
|
||||
print("No get_indian_news_api provider found!")
|
||||
return None
|
||||
|
||||
def find_agents_needing_indian_news(connection):
|
||||
"""Find agents that have other news plugins but missing indian news"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Find agents that have get_news_from_newsnow (other news plugin)
|
||||
cursor.execute("""
|
||||
SELECT DISTINCT a.id, a.agent_name
|
||||
FROM ai_agent a
|
||||
JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'get_news_from_newsnow'
|
||||
""")
|
||||
|
||||
news_agents = cursor.fetchall()
|
||||
|
||||
# Filter out agents that already have indian news
|
||||
agents_needing_indian_news = []
|
||||
|
||||
for agent_id, agent_name in news_agents:
|
||||
cursor.execute("""
|
||||
SELECT COUNT(*)
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE m.agent_id = %s AND p.provider_code = 'get_indian_news_api'
|
||||
""", (agent_id,))
|
||||
|
||||
count = cursor.fetchone()[0]
|
||||
if count == 0:
|
||||
agents_needing_indian_news.append((agent_id, agent_name))
|
||||
|
||||
cursor.close()
|
||||
return agents_needing_indian_news
|
||||
|
||||
def add_indian_news_to_agents(connection, provider_id, agents):
|
||||
"""Add indian news plugin to specified agents"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
added_count = 0
|
||||
|
||||
for agent_id, agent_name in agents:
|
||||
try:
|
||||
cursor.execute("""
|
||||
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
|
||||
VALUES (%s, %s, '{}')
|
||||
""", (agent_id, provider_id))
|
||||
|
||||
print(f"Added get_indian_news_api to {agent_name} ({agent_id})")
|
||||
added_count += 1
|
||||
|
||||
except Error as e:
|
||||
print(f"Error adding to {agent_name}: {e}")
|
||||
|
||||
if added_count > 0:
|
||||
try:
|
||||
connection.commit()
|
||||
print(f"\n[SUCCESS] Added get_indian_news_api to {added_count} agents!")
|
||||
except Error as e:
|
||||
connection.rollback()
|
||||
print(f"\n[ERROR] Failed to commit changes: {e}")
|
||||
return False
|
||||
|
||||
cursor.close()
|
||||
return True
|
||||
|
||||
def verify_additions(connection):
|
||||
"""Verify that the additions were successful"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== VERIFICATION ===")
|
||||
|
||||
# Check agents that now have indian news
|
||||
cursor.execute("""
|
||||
SELECT a.agent_name, COUNT(*) as plugin_count
|
||||
FROM ai_agent a
|
||||
JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'get_indian_news_api'
|
||||
GROUP BY a.id, a.agent_name
|
||||
ORDER BY a.agent_name
|
||||
""")
|
||||
|
||||
agents_with_indian_news = cursor.fetchall()
|
||||
|
||||
if agents_with_indian_news:
|
||||
print(f"Agents with get_indian_news_api:")
|
||||
for agent_name, count in agents_with_indian_news:
|
||||
print(f" - {agent_name}")
|
||||
else:
|
||||
print("No agents have get_indian_news_api plugin!")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
print("=== ADDING MISSING get_indian_news_api ===\n")
|
||||
|
||||
# 1. Check if provider exists
|
||||
provider_id = check_indian_news_provider(connection)
|
||||
if not provider_id:
|
||||
print("[ERROR] get_indian_news_api provider not found in database!")
|
||||
print("You may need to add it first to ai_model_provider table")
|
||||
return
|
||||
|
||||
# 2. Find agents that need it
|
||||
agents_needing = find_agents_needing_indian_news(connection)
|
||||
|
||||
if not agents_needing:
|
||||
print("[INFO] All agents already have get_indian_news_api or no agents have news plugins")
|
||||
return
|
||||
|
||||
print(f"Found {len(agents_needing)} agents that need get_indian_news_api:")
|
||||
for agent_id, agent_name in agents_needing:
|
||||
print(f" - {agent_name} ({agent_id})")
|
||||
|
||||
# 3. Ask for confirmation
|
||||
response = input(f"\nAdd get_indian_news_api to these {len(agents_needing)} agents? (y/N): ").strip().lower()
|
||||
|
||||
if response == 'y' or response == 'yes':
|
||||
# 4. Add the mappings
|
||||
success = add_indian_news_to_agents(connection, provider_id, agents_needing)
|
||||
|
||||
if success:
|
||||
# 5. Verify
|
||||
verify_additions(connection)
|
||||
print(f"\n[COMPLETE] get_indian_news_api has been added to agents!")
|
||||
print("\nNext steps:")
|
||||
print("1. Restart manager-api to reload configurations")
|
||||
print("2. Test get_indian_news_api functionality")
|
||||
else:
|
||||
print(f"\n[FAILED] Could not add get_indian_news_api to agents")
|
||||
else:
|
||||
print("No changes made.")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -68,7 +68,7 @@ async def main():
|
|||
|
||||
if not read_config_from_api:
|
||||
logger.bind(tag=TAG).info(
|
||||
"OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
|
||||
"OTA interface is\t\thttp://{}:{}/toy/ota/",
|
||||
get_local_ip(),
|
||||
port,
|
||||
)
|
||||
|
|
@ -98,7 +98,7 @@ async def main():
|
|||
websocket_port = int(server_config.get("port", 8000))
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
"Websocket address is\tws://{}:{}/xiaozhi/v1/",
|
||||
"Websocket address is\tws://{}:{}/toy/v1/",
|
||||
get_local_ip(),
|
||||
websocket_port,
|
||||
)
|
||||
|
|
|
|||
110
main/xiaozhi-server/check_database.py
Normal file
110
main/xiaozhi-server/check_database.py
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to check what's in the Railway MySQL database
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration from application-dev.yml
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Successfully connected to Railway MySQL database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Error connecting to MySQL database: {e}")
|
||||
return None
|
||||
|
||||
def check_tables(connection):
|
||||
"""Check what tables exist in the database"""
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SHOW TABLES")
|
||||
tables = cursor.fetchall()
|
||||
print(f"\nFound {len(tables)} tables:")
|
||||
for table in tables:
|
||||
print(f" - {table[0]}")
|
||||
cursor.close()
|
||||
return [table[0] for table in tables]
|
||||
|
||||
def check_config_tables(connection):
|
||||
"""Check configuration-related tables"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Check system parameters table
|
||||
print("\n=== System Parameters ===")
|
||||
try:
|
||||
cursor.execute("SELECT param_key, param_value FROM sys_params WHERE param_key LIKE '%log%' OR param_key LIKE '%config%'")
|
||||
params = cursor.fetchall()
|
||||
for param in params:
|
||||
print(f" {param[0]}: {param[1]}")
|
||||
except Error as e:
|
||||
print(f"Error querying sys_params: {e}")
|
||||
|
||||
# Check AI model configurations
|
||||
print("\n=== AI Model Configurations ===")
|
||||
try:
|
||||
cursor.execute("SELECT id, model_type, name, config_json FROM ai_model_config WHERE model_type = 'LLM' LIMIT 5")
|
||||
models = cursor.fetchall()
|
||||
for model in models:
|
||||
print(f" ID: {model[0]}")
|
||||
print(f" Type: {model[1]}")
|
||||
print(f" Name: {model[2]}")
|
||||
try:
|
||||
config = json.loads(model[3]) if model[3] else {}
|
||||
print(f" Config: {json.dumps(config, indent=4)}")
|
||||
except:
|
||||
print(f" Config: {model[3]}")
|
||||
print(" ---")
|
||||
except Error as e:
|
||||
print(f"Error querying ai_model_config: {e}")
|
||||
|
||||
# Check server configurations
|
||||
print("\n=== Server Configurations ===")
|
||||
try:
|
||||
cursor.execute("SELECT * FROM server_config LIMIT 5")
|
||||
servers = cursor.fetchall()
|
||||
columns = [desc[0] for desc in cursor.description]
|
||||
for server in servers:
|
||||
server_dict = dict(zip(columns, server))
|
||||
print(f" Server: {json.dumps(server_dict, indent=2, default=str)}")
|
||||
except Error as e:
|
||||
print(f"Error querying server_config: {e}")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
"""Main function to check the database"""
|
||||
print("Connecting to Railway MySQL database...")
|
||||
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
tables = check_tables(connection)
|
||||
check_config_tables(connection)
|
||||
|
||||
except Error as e:
|
||||
print(f"Error during database operations: {e}")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
print("\nDatabase connection closed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
104
main/xiaozhi-server/check_database_structure.py
Normal file
104
main/xiaozhi-server/check_database_structure.py
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to check the actual database table structures
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration from application-dev.yml
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Successfully connected to Railway MySQL database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Error connecting to MySQL database: {e}")
|
||||
return None
|
||||
|
||||
def describe_table(connection, table_name):
|
||||
"""Describe the structure of a table"""
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(f"DESCRIBE {table_name}")
|
||||
columns = cursor.fetchall()
|
||||
print(f"\n=== Table: {table_name} ===")
|
||||
for col in columns:
|
||||
print(f" {col[0]} | {col[1]} | {col[2]} | {col[3]} | {col[4]} | {col[5]}")
|
||||
return [col[0] for col in columns]
|
||||
except Error as e:
|
||||
print(f"Error describing table {table_name}: {e}")
|
||||
return []
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def check_sys_params(connection):
|
||||
"""Check sys_params table structure and content"""
|
||||
cursor = connection.cursor()
|
||||
columns = describe_table(connection, 'sys_params')
|
||||
|
||||
try:
|
||||
# Get a few sample records
|
||||
cursor.execute("SELECT * FROM sys_params LIMIT 10")
|
||||
rows = cursor.fetchall()
|
||||
print(f"\nSample data from sys_params:")
|
||||
for row in rows:
|
||||
row_dict = dict(zip(columns, row))
|
||||
print(f" {json.dumps(row_dict, indent=2, default=str)}")
|
||||
except Error as e:
|
||||
print(f"Error querying sys_params: {e}")
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def check_ai_model_config(connection):
|
||||
"""Check ai_model_config table structure and content"""
|
||||
cursor = connection.cursor()
|
||||
columns = describe_table(connection, 'ai_model_config')
|
||||
|
||||
try:
|
||||
# Get LLM configs
|
||||
cursor.execute("SELECT * FROM ai_model_config WHERE model_type = 'LLM' LIMIT 5")
|
||||
rows = cursor.fetchall()
|
||||
print(f"\nLLM configurations from ai_model_config:")
|
||||
for row in rows:
|
||||
row_dict = dict(zip(columns, row))
|
||||
print(f" {json.dumps(row_dict, indent=2, default=str)}")
|
||||
except Error as e:
|
||||
print(f"Error querying ai_model_config: {e}")
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# Check key tables
|
||||
check_sys_params(connection)
|
||||
check_ai_model_config(connection)
|
||||
|
||||
except Error as e:
|
||||
print(f"Error during database operations: {e}")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
print("\nDatabase connection closed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
181
main/xiaozhi-server/check_intent_functions.py
Normal file
181
main/xiaozhi-server/check_intent_functions.py
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Check how Intent function_call gets its functions list from manager-api
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Connected to database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Connection error: {e}")
|
||||
return None
|
||||
|
||||
def check_intent_function_call_config(connection):
|
||||
"""Check the Intent function_call configuration"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("=== INTENT FUNCTION_CALL CONFIGURATION ===\n")
|
||||
|
||||
# Check the Intent_function_call config
|
||||
cursor.execute("""
|
||||
SELECT id, model_name, config_json, remark
|
||||
FROM ai_model_config
|
||||
WHERE id = 'Intent_function_call'
|
||||
""")
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
config_id, model_name, config_json, remark = result
|
||||
print(f"Configuration ID: {config_id}")
|
||||
print(f"Model Name: {model_name}")
|
||||
|
||||
try:
|
||||
config = json.loads(config_json) if config_json else {}
|
||||
print(f"Current Config:")
|
||||
print(json.dumps(config, indent=2))
|
||||
|
||||
# Check if functions are defined in config
|
||||
if 'functions' in config:
|
||||
functions = config['functions']
|
||||
print(f"\nFunctions in config: {functions}")
|
||||
else:
|
||||
print("\nNo 'functions' key found in Intent config - uses plugin mappings instead")
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error parsing config JSON: {e}")
|
||||
print(f"Raw config: {config_json}")
|
||||
|
||||
if remark:
|
||||
print(f"\nRemark: {remark}")
|
||||
else:
|
||||
print("Intent_function_call configuration not found!")
|
||||
return False
|
||||
|
||||
cursor.close()
|
||||
return True
|
||||
|
||||
def check_how_functions_are_loaded(connection):
|
||||
"""Check how functions are loaded for agents"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== HOW FUNCTIONS ARE LOADED FOR AGENTS ===\n")
|
||||
|
||||
# Check a specific agent and its plugin mappings
|
||||
cursor.execute("""
|
||||
SELECT a.id, a.agent_name, a.intent_model_id
|
||||
FROM ai_agent a
|
||||
WHERE a.agent_name LIKE '%Cheeko%'
|
||||
LIMIT 1
|
||||
""")
|
||||
agent_result = cursor.fetchone()
|
||||
|
||||
if not agent_result:
|
||||
print("No Cheeko agent found")
|
||||
return
|
||||
|
||||
agent_id, agent_name, intent_model = agent_result
|
||||
print(f"Checking agent: {agent_name} ({agent_id})")
|
||||
print(f"Intent model: {intent_model}")
|
||||
|
||||
# Get plugins for this agent
|
||||
print(f"\nPlugins mapped to this agent:")
|
||||
cursor.execute("""
|
||||
SELECT p.id, p.provider_code, p.name, m.param_info
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE m.agent_id = %s AND p.model_type = 'Plugin'
|
||||
ORDER BY p.provider_code
|
||||
""", (agent_id,))
|
||||
|
||||
plugins = cursor.fetchall()
|
||||
|
||||
if plugins:
|
||||
available_functions = []
|
||||
for plugin in plugins:
|
||||
provider_id, provider_code, provider_name, param_info = plugin
|
||||
available_functions.append(provider_code)
|
||||
print(f" - {provider_code} ({provider_name})")
|
||||
|
||||
print(f"\nAvailable functions for this agent: {available_functions}")
|
||||
|
||||
# Check specifically for our functions
|
||||
expected_functions = ['play_music', 'play_story', 'get_weather', 'get_indian_news_api', 'get_news_from_newsnow']
|
||||
missing_functions = []
|
||||
present_functions = []
|
||||
|
||||
for func in expected_functions:
|
||||
if func in available_functions:
|
||||
present_functions.append(func)
|
||||
else:
|
||||
missing_functions.append(func)
|
||||
|
||||
print(f"\nFunction Status:")
|
||||
print(f" Present: {present_functions}")
|
||||
print(f" Missing: {missing_functions}")
|
||||
|
||||
if missing_functions:
|
||||
print(f"\n[WARNING] Missing functions: {missing_functions}")
|
||||
print("These functions won't be available when using manager-api config")
|
||||
else:
|
||||
print(f"\n[OK] All expected functions are available!")
|
||||
|
||||
else:
|
||||
print("No plugin mappings found for this agent")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def check_server_config_generation(connection):
|
||||
"""Check how server config is generated"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== SERVER CONFIG GENERATION LOGIC ===\n")
|
||||
|
||||
# This is what the server likely does when generating config
|
||||
print("The server config generation likely works as follows:")
|
||||
print("1. Gets basic Intent configuration from ai_model_config")
|
||||
print("2. For each agent request, gets plugins from ai_agent_plugin_mapping")
|
||||
print("3. Dynamically builds the functions list based on agent's plugins")
|
||||
print("")
|
||||
print("This means the 'functions' are not in the Intent config itself,")
|
||||
print("but are loaded per-agent from the plugin mappings.")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# Check Intent configuration
|
||||
if check_intent_function_call_config(connection):
|
||||
# Check how functions are loaded for agents
|
||||
check_how_functions_are_loaded(connection)
|
||||
# Explain server config generation
|
||||
check_server_config_generation(connection)
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
127
main/xiaozhi-server/check_log_config.py
Normal file
127
main/xiaozhi-server/check_log_config.py
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to check and fix log configuration in database
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Successfully connected to Railway MySQL database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Error connecting to MySQL database: {e}")
|
||||
return None
|
||||
|
||||
def check_log_parameters(connection):
|
||||
"""Check log-related parameters"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
try:
|
||||
# Check for log-related parameters
|
||||
cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_code LIKE '%log%'")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print("=== Log-related Parameters ===")
|
||||
for row in rows:
|
||||
print(f"ID: {row[0]} | Code: {row[1]} | Value: {row[2]}")
|
||||
|
||||
return rows
|
||||
except Error as e:
|
||||
print(f"Error querying log parameters: {e}")
|
||||
return []
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def fix_log_level_if_needed(connection):
|
||||
"""Fix log level if it's corrupted"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
try:
|
||||
# Check if there's a corrupted log_level parameter
|
||||
cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_value LIKE '%http%' AND param_value LIKE '%ota%'")
|
||||
corrupted_rows = cursor.fetchall()
|
||||
|
||||
if corrupted_rows:
|
||||
print(f"\nFound {len(corrupted_rows)} corrupted parameters:")
|
||||
for row in corrupted_rows:
|
||||
print(f" ID: {row[0]} | Code: {row[1]} | Value: {row[2]}")
|
||||
|
||||
# Fix the corrupted log level
|
||||
for row in corrupted_rows:
|
||||
if 'log' in row[1].lower(): # If it's a log-related parameter
|
||||
print(f"\nFixing parameter {row[1]} (ID: {row[0]})")
|
||||
cursor.execute(
|
||||
"UPDATE sys_params SET param_value = %s, update_date = NOW() WHERE id = %s",
|
||||
("INFO", row[0])
|
||||
)
|
||||
connection.commit()
|
||||
print(f"✅ Fixed: {row[1]} set to 'INFO'")
|
||||
else:
|
||||
print("\nNo corrupted log parameters found.")
|
||||
|
||||
except Error as e:
|
||||
print(f"Error fixing log parameters: {e}")
|
||||
connection.rollback()
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def check_all_params_with_urls(connection):
|
||||
"""Check all parameters that might have URLs incorrectly"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_value LIKE '%http%'")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"\n=== All Parameters with HTTP URLs ===")
|
||||
for row in rows:
|
||||
print(f"ID: {row[0]} | Code: {row[1]} | Value: {row[2]}")
|
||||
|
||||
except Error as e:
|
||||
print(f"Error querying URL parameters: {e}")
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
check_log_parameters(connection)
|
||||
check_all_params_with_urls(connection)
|
||||
fix_log_level_if_needed(connection)
|
||||
|
||||
# Check again after fix
|
||||
print("\n" + "="*50)
|
||||
print("After fix:")
|
||||
check_log_parameters(connection)
|
||||
|
||||
except Error as e:
|
||||
print(f"Error during database operations: {e}")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
print("\nDatabase connection closed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
305
main/xiaozhi-server/check_plugin_mappings.py
Normal file
305
main/xiaozhi-server/check_plugin_mappings.py
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script to check plugin mappings and agent configurations in the database
|
||||
This will help us understand how play_music is configured and what's needed for play_story
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
import sys
|
||||
from mysql.connector import Error
|
||||
|
||||
# Set UTF-8 encoding for Windows console
|
||||
if sys.platform == "win32":
|
||||
import os
|
||||
os.system("chcp 65001 >nul 2>&1")
|
||||
|
||||
def safe_print(text):
|
||||
"""Safely print text with UTF-8 encoding"""
|
||||
try:
|
||||
print(text)
|
||||
except UnicodeEncodeError:
|
||||
print(text.encode('utf-8', errors='replace').decode('utf-8'))
|
||||
|
||||
# Database configuration from application-dev.yml
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Successfully connected to Railway MySQL database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Error connecting to MySQL database: {e}")
|
||||
return None
|
||||
|
||||
def check_plugin_providers(connection):
|
||||
"""Check available plugin providers"""
|
||||
cursor = connection.cursor()
|
||||
print("\n=== Plugin Providers ===")
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, provider_code, name, fields, sort
|
||||
FROM ai_model_provider
|
||||
WHERE model_type = 'Plugin'
|
||||
ORDER BY sort
|
||||
""")
|
||||
providers = cursor.fetchall()
|
||||
|
||||
print(f"Found {len(providers)} plugin providers:")
|
||||
for provider in providers:
|
||||
safe_print(f" ID: {provider[0]}")
|
||||
safe_print(f" Code: {provider[1]}")
|
||||
safe_print(f" Name: {provider[2]}")
|
||||
safe_print(f" Sort: {provider[4]}")
|
||||
try:
|
||||
fields = json.loads(provider[3]) if provider[3] else []
|
||||
if fields:
|
||||
safe_print(f" Fields: {json.dumps(fields, indent=4)}")
|
||||
else:
|
||||
safe_print(" Fields: (none)")
|
||||
except:
|
||||
safe_print(f" Fields: {provider[3]}")
|
||||
safe_print(" ---")
|
||||
except Error as e:
|
||||
print(f"Error querying plugin providers: {e}")
|
||||
cursor.close()
|
||||
|
||||
def check_function_call_config(connection):
|
||||
"""Check function_call intent configuration"""
|
||||
cursor = connection.cursor()
|
||||
print("\n=== Function Call Configuration ===")
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, name, config_json, remark
|
||||
FROM ai_model_config
|
||||
WHERE id = 'Intent_function_call'
|
||||
""")
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
print(f"ID: {result[0]}")
|
||||
print(f"Name: {result[1]}")
|
||||
try:
|
||||
config = json.loads(result[2]) if result[2] else {}
|
||||
print(f"Config: {json.dumps(config, indent=2)}")
|
||||
except:
|
||||
print(f"Config: {result[2]}")
|
||||
print(f"Remark: {result[3]}")
|
||||
else:
|
||||
print("No function_call configuration found!")
|
||||
except Error as e:
|
||||
print(f"Error querying function_call config: {e}")
|
||||
cursor.close()
|
||||
|
||||
def check_agents(connection):
|
||||
"""Check available agents"""
|
||||
cursor = connection.cursor()
|
||||
print("\n=== Available Agents ===")
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, name, intent_provider, creator, create_date
|
||||
FROM ai_agent
|
||||
ORDER BY create_date DESC
|
||||
LIMIT 10
|
||||
""")
|
||||
agents = cursor.fetchall()
|
||||
|
||||
print(f"Found {len(agents)} recent agents:")
|
||||
for agent in agents:
|
||||
print(f" ID: {agent[0]}")
|
||||
print(f" Name: {agent[1]}")
|
||||
print(f" Intent Provider: {agent[2]}")
|
||||
print(f" Creator: {agent[3]}")
|
||||
print(f" Created: {agent[4]}")
|
||||
print(" ---")
|
||||
except Error as e:
|
||||
print(f"Error querying agents: {e}")
|
||||
cursor.close()
|
||||
return agents
|
||||
|
||||
def check_plugin_mappings(connection, agents):
|
||||
"""Check plugin mappings for agents"""
|
||||
cursor = connection.cursor()
|
||||
print("\n=== Agent Plugin Mappings ===")
|
||||
|
||||
for agent in agents:
|
||||
agent_id = agent[0]
|
||||
agent_name = agent[1]
|
||||
|
||||
print(f"\nAgent: {agent_name} ({agent_id})")
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT m.plugin_id, p.provider_code, p.name, m.param_info
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE m.agent_id = %s
|
||||
ORDER BY p.sort
|
||||
""", (agent_id,))
|
||||
mappings = cursor.fetchall()
|
||||
|
||||
if mappings:
|
||||
print(f" Plugins ({len(mappings)}):")
|
||||
for mapping in mappings:
|
||||
print(f" - {mapping[1]} ({mapping[2]})")
|
||||
if mapping[3]:
|
||||
try:
|
||||
params = json.loads(mapping[3])
|
||||
if params:
|
||||
print(f" Params: {json.dumps(params, indent=6)}")
|
||||
except:
|
||||
print(f" Params: {mapping[3]}")
|
||||
else:
|
||||
print(" No plugin mappings found")
|
||||
except Error as e:
|
||||
print(f" Error querying plugin mappings for {agent_name}: {e}")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def check_play_story_status(connection):
|
||||
"""Check if play_story plugin exists"""
|
||||
cursor = connection.cursor()
|
||||
print("\n=== Play Story Status Check ===")
|
||||
|
||||
# Check if play_story provider exists
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT id, provider_code, name
|
||||
FROM ai_model_provider
|
||||
WHERE provider_code = 'play_story' OR id LIKE '%STORY%'
|
||||
""")
|
||||
story_providers = cursor.fetchall()
|
||||
|
||||
if story_providers:
|
||||
print("✓ Play Story provider found:")
|
||||
for provider in story_providers:
|
||||
print(f" - {provider[0]}: {provider[1]} ({provider[2]})")
|
||||
else:
|
||||
print("✗ Play Story provider NOT found")
|
||||
except Error as e:
|
||||
print(f"Error checking play_story provider: {e}")
|
||||
|
||||
# Check if any agents have play_story mapped
|
||||
try:
|
||||
cursor.execute("""
|
||||
SELECT a.name, a.id, m.plugin_id
|
||||
FROM ai_agent a
|
||||
JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'play_story'
|
||||
""")
|
||||
story_mappings = cursor.fetchall()
|
||||
|
||||
if story_mappings:
|
||||
print("✓ Agents with play_story mapping:")
|
||||
for mapping in story_mappings:
|
||||
print(f" - {mapping[0]} ({mapping[1]})")
|
||||
else:
|
||||
print("✗ No agents have play_story mapping")
|
||||
except Error as e:
|
||||
print(f"Error checking play_story mappings: {e}")
|
||||
|
||||
cursor.close()
|
||||
|
||||
def generate_sql_script():
|
||||
"""Generate the SQL script to add play_story support"""
|
||||
timestamp = "202508291600" # Current timestamp
|
||||
|
||||
sql_content = f"""-- Add play_story plugin support to all agents
|
||||
-- Generated automatically to match the pattern of existing plugins like play_music
|
||||
|
||||
-- 1. Add play_story plugin provider (if not exists)
|
||||
DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY';
|
||||
INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date)
|
||||
VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', '服务器故事播放', JSON_ARRAY(), 25, 0, NOW(), 0, NOW());
|
||||
|
||||
-- 2. Add play_story plugin to all existing agents that have play_music
|
||||
-- This ensures consistency - if an agent can play music, it should also be able to play stories
|
||||
INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info)
|
||||
SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{{}}'
|
||||
FROM ai_agent_plugin_mapping m
|
||||
JOIN ai_model_provider p ON p.id = m.plugin_id
|
||||
WHERE p.provider_code = 'play_music'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ai_agent_plugin_mapping m2
|
||||
JOIN ai_model_provider p2 ON p2.id = m2.plugin_id
|
||||
WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story'
|
||||
);
|
||||
|
||||
-- 3. Update documentation
|
||||
UPDATE `ai_model_provider` SET
|
||||
`fields` = JSON_ARRAY(
|
||||
JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', '故事文件存放路径', 'default', './stories'),
|
||||
JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', '故事文件类型', 'default', '.mp3;.wav;.p3'),
|
||||
JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', '故事列表刷新间隔(秒)', 'default', '300')
|
||||
)
|
||||
WHERE id = 'SYSTEM_PLUGIN_STORY';
|
||||
"""
|
||||
|
||||
# Write SQL file
|
||||
sql_file_path = f"d:\\cheekofinal\\xiaozhi-esp32-server\\main\\manager-api\\src\\main\\resources\\db\\changelog\\{timestamp}_add_play_story.sql"
|
||||
with open(sql_file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(sql_content)
|
||||
|
||||
# Generate changelog entry
|
||||
changelog_entry = f""" - changeSet:
|
||||
id: {timestamp}
|
||||
author: claude
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/{timestamp}_add_play_story.sql"""
|
||||
|
||||
print(f"\n=== Generated Files ===")
|
||||
print(f"SQL Script: {sql_file_path}")
|
||||
print("\nAdd this to db.changelog-master.yaml:")
|
||||
print(changelog_entry)
|
||||
|
||||
return sql_file_path
|
||||
|
||||
def main():
|
||||
"""Main function to check plugin mappings and generate SQL"""
|
||||
print("Checking plugin mappings and agent configurations...")
|
||||
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# Check current state
|
||||
check_plugin_providers(connection)
|
||||
check_function_call_config(connection)
|
||||
agents = check_agents(connection)
|
||||
check_plugin_mappings(connection, agents)
|
||||
check_play_story_status(connection)
|
||||
|
||||
# Generate SQL script
|
||||
sql_file = generate_sql_script()
|
||||
|
||||
print(f"\n=== Summary ===")
|
||||
print("1. Check the current plugin mappings above")
|
||||
print("2. Run the generated SQL script to add play_story support")
|
||||
print("3. Update db.changelog-master.yaml with the new changeset")
|
||||
print("4. Restart the manager-api to apply the changes")
|
||||
|
||||
except Error as e:
|
||||
print(f"Error during database operations: {e}")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
print("\nDatabase connection closed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
255
main/xiaozhi-server/check_tts_config.py
Normal file
255
main/xiaozhi-server/check_tts_config.py
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Check and update TTS EdgeTTS voice configuration in database
|
||||
"""
|
||||
import mysql.connector
|
||||
import json
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def connect_to_database():
|
||||
"""Connect to the Railway MySQL database"""
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
if connection.is_connected():
|
||||
print("Connected to database")
|
||||
return connection
|
||||
except Error as e:
|
||||
print(f"Connection error: {e}")
|
||||
return None
|
||||
|
||||
def check_tts_configurations(connection):
|
||||
"""Check TTS configurations in database"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("=== TTS CONFIGURATION CHECK ===\n")
|
||||
|
||||
# First, check available columns
|
||||
try:
|
||||
cursor.execute("DESCRIBE ai_model_config")
|
||||
columns = cursor.fetchall()
|
||||
config_columns = [col[0] for col in columns]
|
||||
print(f"Available ai_model_config columns: {config_columns}")
|
||||
|
||||
# Use correct column names
|
||||
name_col = 'name' if 'name' in config_columns else ('model_name' if 'model_name' in config_columns else 'id')
|
||||
|
||||
# 1. Check ai_model_config for TTS entries
|
||||
print("\n1. TTS Model Configurations:")
|
||||
cursor.execute(f"""
|
||||
SELECT id, model_type, {name_col}, config_json
|
||||
FROM ai_model_config
|
||||
WHERE model_type = 'TTS'
|
||||
ORDER BY id
|
||||
""")
|
||||
except Error as e:
|
||||
print(f"Error checking columns: {e}")
|
||||
return []
|
||||
tts_configs = cursor.fetchall()
|
||||
|
||||
edgetts_configs = []
|
||||
|
||||
if tts_configs:
|
||||
for config in tts_configs:
|
||||
print(f" ID: {config[0]}")
|
||||
print(f" Name: {config[2]}")
|
||||
try:
|
||||
config_json = json.loads(config[3]) if config[3] else {}
|
||||
print(f" Config: {json.dumps(config_json, indent=4)}")
|
||||
|
||||
# Check if this is EdgeTTS and has voice config
|
||||
if config_json.get('type') == 'edge' or 'edge' in config[0].lower():
|
||||
voice = config_json.get('voice', 'Not specified')
|
||||
print(f" >>> EdgeTTS Voice: {voice}")
|
||||
if voice == 'en-GB-MaisieNeural':
|
||||
print(f" >>> NEEDS UPDATE: Found en-GB-MaisieNeural")
|
||||
edgetts_configs.append({
|
||||
'id': config[0],
|
||||
'name': config[2],
|
||||
'config': config_json,
|
||||
'needs_update': True
|
||||
})
|
||||
elif voice == 'en-US-JennyNeural':
|
||||
print(f" >>> OK: Already using en-US-JennyNeural")
|
||||
edgetts_configs.append({
|
||||
'id': config[0],
|
||||
'name': config[2],
|
||||
'config': config_json,
|
||||
'needs_update': False
|
||||
})
|
||||
else:
|
||||
edgetts_configs.append({
|
||||
'id': config[0],
|
||||
'name': config[2],
|
||||
'config': config_json,
|
||||
'needs_update': False,
|
||||
'current_voice': voice
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print(f" Config: {config[3]} (Invalid JSON)")
|
||||
print(" ---")
|
||||
else:
|
||||
print(" No TTS configurations found")
|
||||
|
||||
# 2. Check ai_model_provider for TTS providers
|
||||
print("\n2. TTS Model Providers:")
|
||||
try:
|
||||
cursor.execute("DESCRIBE ai_model_provider")
|
||||
provider_columns = [col[0] for col in cursor.fetchall()]
|
||||
provider_name_col = 'name' if 'name' in provider_columns else ('provider_name' if 'provider_name' in provider_columns else 'id')
|
||||
|
||||
cursor.execute(f"""
|
||||
SELECT id, provider_code, {provider_name_col}, fields
|
||||
FROM ai_model_provider
|
||||
WHERE model_type = 'TTS'
|
||||
ORDER BY provider_code
|
||||
""")
|
||||
except Error as e:
|
||||
print(f"Error checking provider columns: {e}")
|
||||
cursor.execute("""
|
||||
SELECT id, provider_code, fields
|
||||
FROM ai_model_provider
|
||||
WHERE model_type = 'TTS'
|
||||
ORDER BY provider_code
|
||||
""")
|
||||
tts_providers = cursor.fetchall()
|
||||
|
||||
if tts_providers:
|
||||
for provider in tts_providers:
|
||||
print(f" ID: {provider[0]}")
|
||||
print(f" Code: {provider[1]}")
|
||||
if len(provider) > 2:
|
||||
print(f" Name: {provider[2]}")
|
||||
fields_idx = 3
|
||||
else:
|
||||
fields_idx = 2
|
||||
|
||||
if len(provider) > fields_idx:
|
||||
try:
|
||||
fields = json.loads(provider[fields_idx]) if provider[fields_idx] else []
|
||||
if fields:
|
||||
print(f" Fields: {json.dumps(fields, indent=4)}")
|
||||
else:
|
||||
print(" Fields: (none)")
|
||||
except:
|
||||
print(f" Fields: {provider[fields_idx]}")
|
||||
print(" ---")
|
||||
else:
|
||||
print(" No TTS providers found")
|
||||
|
||||
# 3. Check agents and their TTS assignments
|
||||
print("\n3. Agent TTS Assignments:")
|
||||
cursor.execute("""
|
||||
SELECT a.id, a.agent_name, a.tts_model_id, a.tts_voice_id
|
||||
FROM ai_agent a
|
||||
WHERE a.tts_model_id IS NOT NULL OR a.tts_voice_id IS NOT NULL
|
||||
ORDER BY a.agent_name
|
||||
""")
|
||||
agent_tts = cursor.fetchall()
|
||||
|
||||
if agent_tts:
|
||||
for agent in agent_tts:
|
||||
print(f" Agent: {agent[1]} ({agent[0]})")
|
||||
print(f" TTS Model: {agent[2] if agent[2] else 'Not set'}")
|
||||
print(f" TTS Voice: {agent[3] if agent[3] else 'Not set'}")
|
||||
print(" ---")
|
||||
else:
|
||||
print(" No agents with TTS assignments found")
|
||||
|
||||
cursor.close()
|
||||
return edgetts_configs
|
||||
|
||||
def update_edgetts_voice(connection, edgetts_configs):
|
||||
"""Update EdgeTTS voice configurations"""
|
||||
cursor = connection.cursor()
|
||||
|
||||
print("\n=== UPDATING EDGETTS VOICE ===\n")
|
||||
|
||||
updates_made = 0
|
||||
|
||||
for config_info in edgetts_configs:
|
||||
if config_info.get('needs_update', False):
|
||||
config_id = config_info['id']
|
||||
current_config = config_info['config']
|
||||
|
||||
# Update the voice
|
||||
current_config['voice'] = 'en-US-JennyNeural'
|
||||
|
||||
# Update in database
|
||||
try:
|
||||
cursor.execute("""
|
||||
UPDATE ai_model_config
|
||||
SET config_json = %s
|
||||
WHERE id = %s
|
||||
""", (json.dumps(current_config), config_id))
|
||||
|
||||
print(f"[UPDATED] {config_id}: voice changed to en-US-JennyNeural")
|
||||
updates_made += 1
|
||||
|
||||
except Error as e:
|
||||
print(f"[ERROR] Failed to update {config_id}: {e}")
|
||||
|
||||
if updates_made > 0:
|
||||
try:
|
||||
connection.commit()
|
||||
print(f"\n[SUCCESS] {updates_made} TTS configurations updated successfully!")
|
||||
except Error as e:
|
||||
connection.rollback()
|
||||
print(f"\n[ERROR] Failed to commit changes: {e}")
|
||||
else:
|
||||
print("\n[INFO] No updates needed - all EdgeTTS configs already use correct voice")
|
||||
|
||||
cursor.close()
|
||||
return updates_made
|
||||
|
||||
def main():
|
||||
connection = connect_to_database()
|
||||
if not connection:
|
||||
return
|
||||
|
||||
try:
|
||||
# Check current TTS configurations
|
||||
edgetts_configs = check_tts_configurations(connection)
|
||||
|
||||
# Update if needed
|
||||
if edgetts_configs:
|
||||
needs_update = any(config.get('needs_update', False) for config in edgetts_configs)
|
||||
|
||||
if needs_update:
|
||||
print("\n" + "="*50)
|
||||
print("Found EdgeTTS configurations that need updating!")
|
||||
print("="*50)
|
||||
|
||||
response = input("Do you want to update them? (y/N): ").strip().lower()
|
||||
if response == 'y' or response == 'yes':
|
||||
updates_made = update_edgetts_voice(connection, edgetts_configs)
|
||||
|
||||
if updates_made > 0:
|
||||
print("\n[NEXT STEPS]")
|
||||
print("1. Restart the manager-api to reload configurations")
|
||||
print("2. Test TTS with the new en-US-JennyNeural voice")
|
||||
else:
|
||||
print("\nNo changes made.")
|
||||
else:
|
||||
print("\n[INFO] All EdgeTTS configurations are already using the correct voice!")
|
||||
else:
|
||||
print("\n[INFO] No EdgeTTS configurations found in database")
|
||||
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -19,9 +19,9 @@ import opuslib
|
|||
|
||||
# --- Configuration ---
|
||||
|
||||
SERVER_IP = "192.168.1.105" # !!! UPDATE with your server's local IP address !!!
|
||||
SERVER_IP = "139.59.7.72" # !!! UPDATE with your server's local IP address !!!
|
||||
OTA_PORT = 8002
|
||||
MQTT_BROKER_HOST = "192.168.1.105" # MQTT gateway IP
|
||||
MQTT_BROKER_HOST = "139.59.7.72" # MQTT gateway IP
|
||||
|
||||
|
||||
MQTT_BROKER_PORT = 1883
|
||||
|
|
@ -322,7 +322,7 @@ class TestClient:
|
|||
|
||||
def get_ota_config(self) -> bool:
|
||||
"""Requests OTA configuration from the server."""
|
||||
logger.info(f"▶️ STEP 1: Requesting OTA config from http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/")
|
||||
logger.info(f"▶️ STEP 1: Requesting OTA config from http://{SERVER_IP}:{OTA_PORT}/toy/ota/")
|
||||
try:
|
||||
# Generate a client ID for this session
|
||||
import uuid
|
||||
|
|
@ -335,7 +335,7 @@ class TestClient:
|
|||
},
|
||||
"client_id": session_client_id
|
||||
}
|
||||
response = requests.post(f"http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/", headers=headers, json=data, timeout=5)
|
||||
response = requests.post(f"http://{SERVER_IP}:{OTA_PORT}/toy/ota/", headers=headers, json=data, timeout=5)
|
||||
response.raise_for_status()
|
||||
self.ota_config = response.json()
|
||||
print(f"OTA Config received: {json.dumps(self.ota_config, indent=2)}")
|
||||
|
|
@ -347,7 +347,7 @@ class TestClient:
|
|||
logger.info(f"✅ Got websocket URL from OTA: {self.websocket_url}")
|
||||
else:
|
||||
logger.warning("⚠️ No websocket URL in OTA response, using fallback")
|
||||
self.websocket_url = f"ws://{SERVER_IP}:8000/xiaozhi/v1/"
|
||||
self.websocket_url = f"ws://{SERVER_IP}:8000/toy/v1/"
|
||||
|
||||
# Extract MQTT credentials from OTA response
|
||||
mqtt_info = self.ota_config.get("mqtt", {})
|
||||
|
|
@ -403,6 +403,10 @@ class TestClient:
|
|||
mqtt_broker = mqtt_config.get("broker", MQTT_BROKER_HOST)
|
||||
mqtt_port = mqtt_config.get("port", MQTT_BROKER_PORT)
|
||||
|
||||
logger.info(f"📍 MQTT Config from OTA: {mqtt_config}")
|
||||
logger.info(f"📍 Using MQTT Broker: {mqtt_broker}")
|
||||
logger.info(f"📍 Using MQTT Port: {mqtt_port}")
|
||||
logger.info(f"📍 MQTT Credentials: client_id={self.mqtt_credentials.get('client_id', 'NOT SET')}")
|
||||
logger.info(f"▶️ STEP 2: Connecting to MQTT Gateway at {mqtt_broker}:{mqtt_port}...")
|
||||
|
||||
self.mqtt_client = mqtt_client.Client(
|
||||
|
|
@ -417,16 +421,29 @@ class TestClient:
|
|||
)
|
||||
|
||||
try:
|
||||
logger.info(f"🔄 Connecting to {mqtt_broker}:{mqtt_port}...")
|
||||
logger.info(f"🔄 Attempting connection to MQTT broker...")
|
||||
logger.info(f" Host: {mqtt_broker}")
|
||||
logger.info(f" Port: {mqtt_port}")
|
||||
logger.info(f" Client ID: {self.mqtt_credentials['client_id']}")
|
||||
logger.info(f" Username: {self.mqtt_credentials['username']}")
|
||||
|
||||
self.mqtt_client.connect(mqtt_broker, mqtt_port, 60)
|
||||
self.mqtt_client.loop_start()
|
||||
|
||||
# Wait a moment for connection to establish
|
||||
time.sleep(2)
|
||||
|
||||
# Check if connected
|
||||
if self.mqtt_client.is_connected():
|
||||
logger.info("✅ MQTT client is connected!")
|
||||
else:
|
||||
logger.warning("⚠️ MQTT client connection status unknown, waiting...")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Failed to connect to MQTT Gateway: {e}")
|
||||
logger.error(f" Error type: {type(e).__name__}")
|
||||
logger.error(f" Broker: {mqtt_broker}:{mqtt_port}")
|
||||
return False
|
||||
|
||||
def send_hello_and_get_session(self) -> bool:
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ server:
|
|||
# When deploying with docker or using public network deployment (using SSL, domain names), it may not be accurate
|
||||
# So if you deploy with docker, set websocket to the LAN address
|
||||
# If you deploy on public network, set websocket to the public network address
|
||||
websocket: ws://your-ip-or-domain:port/xiaozhi/v1/
|
||||
websocket: ws://your-ip-or-domain:port/toy/v1/
|
||||
# Visual analysis interface address
|
||||
# Visual analysis interface address sent to devices
|
||||
# If using the default configuration below, the system will automatically generate the visual recognition address and output it in the startup log. You can directly access this address with a browser to confirm
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ class OTAHandler(BaseHandler):
|
|||
|
||||
if not websocket_config or "你的" in websocket_config:
|
||||
print(f"[OTA DEBUG] Using default websocket URL")
|
||||
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
||||
return f"ws://{local_ip}:{port}/toy/v1/"
|
||||
else:
|
||||
print(f"[OTA DEBUG] Using configured websocket URL: {websocket_config}")
|
||||
return websocket_config
|
||||
|
|
|
|||
|
|
@ -255,18 +255,41 @@ class ConnectionHandler:
|
|||
"""Save memory and close the connection"""
|
||||
try:
|
||||
if self.memory:
|
||||
# Log where memory is being saved based on memory type
|
||||
memory_type = getattr(self, 'memory_type', 'unknown')
|
||||
if memory_type == "nomem":
|
||||
self.logger.bind(tag=TAG).info("Memory saving DISABLED (using nomem)")
|
||||
elif memory_type == "mem0ai":
|
||||
self.logger.bind(tag=TAG).info("Saving memory to MEM0 CLOUD")
|
||||
elif memory_type == "mem_local_short":
|
||||
self.logger.bind(tag=TAG).info("Saving memory to LOCAL STORAGE (mem_local_short)")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).info(f"Saving memory using: {memory_type}")
|
||||
|
||||
# Use a thread pool to save memory asynchronously
|
||||
def save_memory_task():
|
||||
try:
|
||||
self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting memory save task for {memory_type}")
|
||||
self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Dialogue messages count: {len(self.dialogue.dialogue) if self.dialogue and self.dialogue.dialogue else 0}")
|
||||
|
||||
# Create a new event loop (to avoid conflicts with the main loop)
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_until_complete(
|
||||
|
||||
self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Calling memory.save_memory()")
|
||||
result = loop.run_until_complete(
|
||||
self.memory.save_memory(self.dialogue.dialogue)
|
||||
)
|
||||
|
||||
if result:
|
||||
self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Memory saved successfully using {memory_type}. Result: {result}")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).warning(f"[MEM0-THREAD] Memory save returned None/False for {memory_type}")
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(
|
||||
f"Failed to save memory: {e}")
|
||||
f"[MEM0-THREAD] Failed to save memory: {e}")
|
||||
self.logger.bind(tag=TAG).error(
|
||||
f"[MEM0-THREAD] Exception traceback: {traceback.format_exc()}")
|
||||
finally:
|
||||
try:
|
||||
loop.close()
|
||||
|
|
@ -274,6 +297,7 @@ class ConnectionHandler:
|
|||
pass
|
||||
|
||||
# Start a thread to save memory, do not wait for completion
|
||||
self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting new thread for memory save")
|
||||
threading.Thread(target=save_memory_task, daemon=True).start()
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
|
||||
|
|
@ -474,6 +498,24 @@ class ConnectionHandler:
|
|||
)
|
||||
private_config["delete_audio"] = bool(
|
||||
self.config.get("delete_audio", True))
|
||||
# Log the actual API key status for debugging (without exposing the full key)
|
||||
if "Memory" in private_config and "Memory_mem0ai" in private_config.get("Memory", {}):
|
||||
mem0_config = private_config["Memory"]["Memory_mem0ai"]
|
||||
api_key = mem0_config.get("api_key", "")
|
||||
|
||||
# DEBUG: Print the full API key to verify what's being received
|
||||
self.logger.bind(tag=TAG).info(f"[DEBUG] Raw mem0 API key received: '{api_key}'")
|
||||
|
||||
if api_key == "***":
|
||||
self.logger.bind(tag=TAG).warning(
|
||||
"Mem0 API key is MASKED (***) from manager API - please configure the actual API key in the Manager Web Dashboard under Provider Management"
|
||||
)
|
||||
elif api_key:
|
||||
masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
|
||||
self.logger.bind(tag=TAG).debug(f"Mem0 API key received: {masked_key} (length: {len(api_key)})")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).warning("Mem0 API key is empty in differential configuration")
|
||||
|
||||
self.logger.bind(tag=TAG).info(
|
||||
f"{time.time() - begin_time} seconds, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
|
||||
)
|
||||
|
|
@ -606,11 +648,16 @@ class ConnectionHandler:
|
|||
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
|
||||
"type"
|
||||
]
|
||||
# Store memory type for logging
|
||||
self.memory_type = memory_type
|
||||
|
||||
# If using nomem, return directly
|
||||
if memory_type == "nomem":
|
||||
self.logger.bind(tag=TAG).info("Memory module initialized: DISABLED (nomem)")
|
||||
return
|
||||
# Use mem_local_short mode
|
||||
elif memory_type == "mem_local_short":
|
||||
self.logger.bind(tag=TAG).info("Memory module initialized: LOCAL STORAGE (mem_local_short)")
|
||||
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
|
||||
"llm"
|
||||
]
|
||||
|
|
@ -632,7 +679,11 @@ class ConnectionHandler:
|
|||
# Otherwise use main LLM
|
||||
self.memory.set_llm(self.llm)
|
||||
self.logger.bind(tag=TAG).info(
|
||||
"Using main LLM as intent recognition model")
|
||||
"Using main LLM as memory model")
|
||||
elif memory_type == "mem0ai":
|
||||
self.logger.bind(tag=TAG).info("Memory module initialized: MEM0 CLOUD (mem0ai)")
|
||||
else:
|
||||
self.logger.bind(tag=TAG).info(f"Memory module initialized: {memory_type}")
|
||||
|
||||
def _initialize_intent(self):
|
||||
if self.intent is None:
|
||||
|
|
@ -1084,6 +1135,12 @@ class ConnectionHandler:
|
|||
# Clear ASR audio buffer to prevent processing leftover audio
|
||||
if hasattr(self, 'asr_audio'):
|
||||
self.asr_audio.clear()
|
||||
# Reset VAD recording start time for timeout
|
||||
if hasattr(self, 'vad_recording_start_time'):
|
||||
delattr(self, 'vad_recording_start_time')
|
||||
# Reset timeout flag
|
||||
if hasattr(self, '_timeout_triggered'):
|
||||
self._timeout_triggered = False
|
||||
# Clear ASR audio queue for this specific connection only
|
||||
if hasattr(self, 'asr_audio_queue'):
|
||||
# Empty the queue by getting all items without blocking
|
||||
|
|
|
|||
|
|
@ -28,6 +28,13 @@ async def handleAudioMessage(conn, audio):
|
|||
|
||||
# Whether the current segment has someone speaking
|
||||
have_voice = conn.vad.is_vad(conn, audio)
|
||||
|
||||
# Track when voice recording starts in auto VAD mode (for 10-second timeout)
|
||||
if have_voice and not hasattr(conn, 'vad_recording_start_time'):
|
||||
conn.vad_recording_start_time = time.time()
|
||||
conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
|
||||
elif have_voice and hasattr(conn, 'vad_recording_start_time'):
|
||||
conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}")
|
||||
|
||||
# Check if this is the initial connection period (ignore first 1 second of audio)
|
||||
if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:
|
||||
|
|
|
|||
|
|
@ -95,8 +95,10 @@ def opus_to_wav(conn, opus_data):
|
|||
|
||||
def enqueue_tts_report(conn, text, opus_data):
|
||||
if not conn.read_config_from_api or conn.need_bind or not conn.report_tts_enable:
|
||||
conn.logger.bind(tag=TAG).info("Chat history NOT SAVED - API config or binding not enabled")
|
||||
return
|
||||
if conn.chat_history_conf == 0:
|
||||
conn.logger.bind(tag=TAG).info("Chat history NOT SAVED - Disabled in configuration (chatHistoryConf = 0)")
|
||||
return
|
||||
"""Add TTS data to reporting queue
|
||||
|
||||
|
|
@ -109,13 +111,13 @@ def enqueue_tts_report(conn, text, opus_data):
|
|||
# Use connection object's queue, pass text and binary data instead of file path
|
||||
if conn.chat_history_conf == 2:
|
||||
conn.report_queue.put((2, text, opus_data, int(time.time())))
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"TTS data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
|
||||
conn.logger.bind(tag=TAG).info(
|
||||
f"Chat history saving to MYSQL DATABASE with TEXT + AUDIO (device: {conn.device_id}, audio size: {len(opus_data)} bytes)"
|
||||
)
|
||||
else:
|
||||
conn.report_queue.put((2, text, None, int(time.time())))
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"TTS data added to reporting queue: {conn.device_id}, no audio reporting"
|
||||
conn.logger.bind(tag=TAG).info(
|
||||
f"Chat history saving to MYSQL DATABASE with TEXT ONLY (device: {conn.device_id})"
|
||||
)
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Failed to add TTS to reporting queue: {text}, {e}")
|
||||
|
|
@ -123,8 +125,10 @@ def enqueue_tts_report(conn, text, opus_data):
|
|||
|
||||
def enqueue_asr_report(conn, text, opus_data):
|
||||
if not conn.read_config_from_api or conn.need_bind or not conn.report_asr_enable:
|
||||
conn.logger.bind(tag=TAG).info("User audio NOT SAVED - API config or binding not enabled")
|
||||
return
|
||||
if conn.chat_history_conf == 0:
|
||||
conn.logger.bind(tag=TAG).info("User audio NOT SAVED - Disabled in configuration (chatHistoryConf = 0)")
|
||||
return
|
||||
"""Add ASR data to reporting queue
|
||||
|
||||
|
|
@ -137,13 +141,13 @@ def enqueue_asr_report(conn, text, opus_data):
|
|||
# Use connection object's queue, pass text and binary data instead of file path
|
||||
if conn.chat_history_conf == 2:
|
||||
conn.report_queue.put((1, text, opus_data, int(time.time())))
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"ASR data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
|
||||
conn.logger.bind(tag=TAG).info(
|
||||
f"User audio saving to MYSQL DATABASE with TEXT + AUDIO (device: {conn.device_id}, audio size: {len(opus_data)} bytes)"
|
||||
)
|
||||
else:
|
||||
conn.report_queue.put((1, text, None, int(time.time())))
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"ASR data added to reporting queue: {conn.device_id}, no audio reporting"
|
||||
conn.logger.bind(tag=TAG).info(
|
||||
f"User audio saving to MYSQL DATABASE with TEXT ONLY (device: {conn.device_id})"
|
||||
)
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).debug(f"Failed to add ASR to reporting queue: {text}, {e}")
|
||||
|
|
@ -29,7 +29,7 @@ class SimpleHttpServer:
|
|||
if websocket_config and "you" not in websocket_config:
|
||||
return websocket_config
|
||||
else:
|
||||
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
||||
return f"ws://{local_ip}:{port}/toy/v1/"
|
||||
|
||||
async def start(self):
|
||||
server_config = self.config["server"]
|
||||
|
|
@ -51,10 +51,10 @@ class SimpleHttpServer:
|
|||
# If smart control panel is not enabled, just running single module, need to add simple OTA interface for delivering websocket interface
|
||||
self.logger.bind(tag=TAG).info("Adding OTA routes")
|
||||
app.add_routes([
|
||||
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
|
||||
web.post("/xiaozhi/ota/",
|
||||
web.get("/toy/ota/", self.ota_handler.handle_get),
|
||||
web.post("/toy/ota/",
|
||||
self.ota_handler.handle_post),
|
||||
web.options("/xiaozhi/ota/",
|
||||
web.options("/toy/ota/",
|
||||
self.ota_handler.handle_post),
|
||||
])
|
||||
|
||||
|
|
|
|||
274
main/xiaozhi-server/core/providers/asr/amazon_transcribe.py
Normal file
274
main/xiaozhi-server/core/providers/asr/amazon_transcribe.py
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
import os
|
||||
import time
|
||||
import asyncio
|
||||
import boto3
|
||||
import json
|
||||
from botocore.exceptions import ClientError, NoCredentialsError
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
"""
|
||||
Amazon Transcribe ASR Provider
|
||||
Uses Amazon Transcribe service for speech-to-text transcription
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__(config)
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
|
||||
# AWS Configuration
|
||||
self.aws_access_key_id = config.get("aws_access_key_id")
|
||||
self.aws_secret_access_key = config.get("aws_secret_access_key")
|
||||
self.aws_region = config.get("aws_region", "us-east-1")
|
||||
self.s3_bucket = config.get("s3_bucket")
|
||||
|
||||
# Transcription Configuration
|
||||
self.language_code = config.get("language_code", "en-US")
|
||||
self.sample_rate = int(config.get("sample_rate", 16000))
|
||||
self.media_format = config.get("media_format", "wav")
|
||||
self.vocabulary_name = config.get("vocabulary_name") # Optional custom vocabulary
|
||||
self.vocabulary_filter_name = config.get("vocabulary_filter_name") # Optional vocabulary filter
|
||||
|
||||
# File management
|
||||
self.output_dir = config.get("output_dir", "./audio_files")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
self.s3_key_prefix = config.get("s3_key_prefix", "xiaozhi-audio/")
|
||||
|
||||
# Timeout configuration
|
||||
timeout = config.get("timeout", 60)
|
||||
self.timeout = int(timeout) if timeout else 60
|
||||
|
||||
# Initialize AWS clients
|
||||
try:
|
||||
session = boto3.Session(
|
||||
aws_access_key_id=self.aws_access_key_id,
|
||||
aws_secret_access_key=self.aws_secret_access_key,
|
||||
region_name=self.aws_region
|
||||
)
|
||||
|
||||
self.transcribe_client = session.client('transcribe')
|
||||
self.s3_client = session.client('s3')
|
||||
|
||||
# Test S3 bucket access
|
||||
self._test_s3_access()
|
||||
|
||||
except NoCredentialsError:
|
||||
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to initialize AWS clients: {e}")
|
||||
raise
|
||||
|
||||
# Ensure output directory exists
|
||||
if not os.path.exists(self.output_dir):
|
||||
os.makedirs(self.output_dir)
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe ASR initialized - Region: {self.aws_region}, "
|
||||
f"Language: {self.language_code}, S3 Bucket: {self.s3_bucket}"
|
||||
)
|
||||
|
||||
def _test_s3_access(self):
|
||||
"""Test S3 bucket access"""
|
||||
try:
|
||||
self.s3_client.head_bucket(Bucket=self.s3_bucket)
|
||||
logger.bind(tag=TAG).info(f"S3 bucket '{self.s3_bucket}' is accessible")
|
||||
except ClientError as e:
|
||||
error_code = e.response['Error']['Code']
|
||||
if error_code == '404':
|
||||
logger.bind(tag=TAG).error(f"S3 bucket '{self.s3_bucket}' does not exist")
|
||||
elif error_code == '403':
|
||||
logger.bind(tag=TAG).error(f"Access denied to S3 bucket '{self.s3_bucket}'")
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"Error accessing S3 bucket: {e}")
|
||||
raise
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Convert speech data to text using Amazon Transcribe"""
|
||||
start_time = time.time()
|
||||
audio_file_path = None
|
||||
s3_key = None
|
||||
job_name = None
|
||||
|
||||
try:
|
||||
# Decode Opus to PCM if needed
|
||||
if audio_format == "opus":
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
if not pcm_data:
|
||||
logger.bind(tag=TAG).error("Failed to decode Opus audio")
|
||||
return None, None
|
||||
else:
|
||||
pcm_data = opus_data
|
||||
|
||||
# Save audio to temporary file
|
||||
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# Calculate audio length for logging
|
||||
audio_length_seconds = len(b"".join(pcm_data)) / (self.sample_rate * 2) # 16-bit audio
|
||||
|
||||
# Upload audio file to S3
|
||||
s3_key = f"{self.s3_key_prefix}{session_id}_{int(time.time())}.wav"
|
||||
|
||||
try:
|
||||
self.s3_client.upload_file(audio_file_path, self.s3_bucket, s3_key)
|
||||
logger.bind(tag=TAG).debug(f"Uploaded audio to S3: s3://{self.s3_bucket}/{s3_key}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to upload to S3: {e}")
|
||||
return None, audio_file_path
|
||||
|
||||
# Create unique job name
|
||||
job_name = f"xiaozhi-transcription-{session_id}-{int(time.time())}"
|
||||
|
||||
# Start transcription job
|
||||
media_uri = f"s3://{self.s3_bucket}/{s3_key}"
|
||||
|
||||
job_args = {
|
||||
'TranscriptionJobName': job_name,
|
||||
'Media': {'MediaFileUri': media_uri},
|
||||
'MediaFormat': self.media_format,
|
||||
'LanguageCode': self.language_code,
|
||||
'MediaSampleRateHertz': self.sample_rate
|
||||
}
|
||||
|
||||
# Add optional parameters
|
||||
if self.vocabulary_name:
|
||||
job_args['Settings'] = job_args.get('Settings', {})
|
||||
job_args['Settings']['VocabularyName'] = self.vocabulary_name
|
||||
|
||||
if self.vocabulary_filter_name:
|
||||
job_args['Settings'] = job_args.get('Settings', {})
|
||||
job_args['Settings']['VocabularyFilterName'] = self.vocabulary_filter_name
|
||||
job_args['Settings']['VocabularyFilterMethod'] = 'remove'
|
||||
|
||||
# Start the transcription job
|
||||
response = self.transcribe_client.start_transcription_job(**job_args)
|
||||
logger.bind(tag=TAG).debug(f"Started transcription job: {job_name}")
|
||||
|
||||
# Poll for job completion
|
||||
result_text = await self._wait_for_job_completion(job_name)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe completed in {elapsed_time:.2f}s: {result_text}"
|
||||
)
|
||||
|
||||
# Log the transcript for debugging/analysis
|
||||
if result_text:
|
||||
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
|
||||
|
||||
return result_text, audio_file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
|
||||
)
|
||||
return None, audio_file_path
|
||||
|
||||
finally:
|
||||
# Clean up audio file if configured
|
||||
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
|
||||
try:
|
||||
os.remove(audio_file_path)
|
||||
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
|
||||
|
||||
# Clean up AWS resources
|
||||
await self._cleanup_aws_resources(job_name, s3_key)
|
||||
|
||||
async def _wait_for_job_completion(self, job_name: str) -> Optional[str]:
|
||||
"""Wait for transcription job to complete and return the result"""
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < self.timeout:
|
||||
try:
|
||||
response = self.transcribe_client.get_transcription_job(
|
||||
TranscriptionJobName=job_name
|
||||
)
|
||||
|
||||
status = response['TranscriptionJob']['TranscriptionJobStatus']
|
||||
|
||||
if status == 'COMPLETED':
|
||||
# Get the transcript
|
||||
transcript_uri = response['TranscriptionJob']['Transcript']['TranscriptFileUri']
|
||||
return await self._fetch_transcript_from_uri(transcript_uri)
|
||||
|
||||
elif status == 'FAILED':
|
||||
failure_reason = response['TranscriptionJob'].get('FailureReason', 'Unknown error')
|
||||
logger.bind(tag=TAG).error(f"Transcription job failed: {failure_reason}")
|
||||
return None
|
||||
|
||||
elif status in ['QUEUED', 'IN_PROGRESS']:
|
||||
# Wait before checking again
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error checking job status: {e}")
|
||||
return None
|
||||
|
||||
logger.bind(tag=TAG).error(f"Transcription job timed out after {self.timeout} seconds")
|
||||
return None
|
||||
|
||||
async def _fetch_transcript_from_uri(self, transcript_uri: str) -> Optional[str]:
|
||||
"""Fetch transcript content from the provided URI"""
|
||||
try:
|
||||
import urllib.request
|
||||
import json
|
||||
|
||||
# Use asyncio to run the blocking operation in a thread
|
||||
loop = asyncio.get_event_loop()
|
||||
response = await loop.run_in_executor(
|
||||
None, urllib.request.urlopen, transcript_uri
|
||||
)
|
||||
|
||||
transcript_data = json.loads(response.read().decode('utf-8'))
|
||||
|
||||
# Extract the transcript text
|
||||
results = transcript_data.get('results', {})
|
||||
transcripts = results.get('transcripts', [])
|
||||
|
||||
if transcripts and len(transcripts) > 0:
|
||||
return transcripts[0].get('transcript', '')
|
||||
else:
|
||||
logger.bind(tag=TAG).warning("No transcript found in response")
|
||||
return ''
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error fetching transcript: {e}")
|
||||
return None
|
||||
|
||||
async def _cleanup_aws_resources(self, job_name: str, s3_key: str):
|
||||
"""Clean up AWS resources"""
|
||||
try:
|
||||
# Delete transcription job (optional, jobs auto-delete after 90 days)
|
||||
if job_name:
|
||||
try:
|
||||
self.transcribe_client.delete_transcription_job(
|
||||
TranscriptionJobName=job_name
|
||||
)
|
||||
logger.bind(tag=TAG).debug(f"Deleted transcription job: {job_name}")
|
||||
except ClientError as e:
|
||||
# Job might not exist or already deleted
|
||||
if e.response['Error']['Code'] != 'BadRequestException':
|
||||
logger.bind(tag=TAG).warning(f"Could not delete job {job_name}: {e}")
|
||||
|
||||
# Delete S3 object
|
||||
if s3_key:
|
||||
try:
|
||||
self.s3_client.delete_object(Bucket=self.s3_bucket, Key=s3_key)
|
||||
logger.bind(tag=TAG).debug(f"Deleted S3 object: {s3_key}")
|
||||
except ClientError as e:
|
||||
logger.bind(tag=TAG).warning(f"Could not delete S3 object {s3_key}: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error during cleanup: {e}")
|
||||
|
|
@ -0,0 +1,333 @@
|
|||
import os
|
||||
import time
|
||||
import asyncio
|
||||
import boto3
|
||||
from amazon_transcribe.client import TranscribeStreamingClient
|
||||
from amazon_transcribe.handlers import TranscriptResultStreamHandler
|
||||
from amazon_transcribe.model import TranscriptEvent, Result
|
||||
from botocore.exceptions import ClientError, NoCredentialsError
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class MyEventHandler(TranscriptResultStreamHandler):
|
||||
"""Custom handler for Amazon Transcribe streaming events"""
|
||||
|
||||
def __init__(self, output_stream):
|
||||
super().__init__(output_stream)
|
||||
self.transcript_parts = []
|
||||
self.final_transcript = ""
|
||||
self.detected_language = None
|
||||
self.language_confidence = None
|
||||
self.is_complete = False
|
||||
|
||||
async def handle_transcript_event(self, transcript_event: TranscriptEvent):
|
||||
"""Handle incoming transcript events"""
|
||||
try:
|
||||
results = transcript_event.transcript.results
|
||||
|
||||
for result in results:
|
||||
# Extract language identification if available
|
||||
if hasattr(result, 'language_identification') and result.language_identification:
|
||||
for lang_id in result.language_identification:
|
||||
if hasattr(lang_id, 'language_code'):
|
||||
self.detected_language = lang_id.language_code
|
||||
if hasattr(lang_id, 'score'):
|
||||
self.language_confidence = lang_id.score
|
||||
logger.bind(tag=TAG).debug(f"Language detected: {self.detected_language} (confidence: {self.language_confidence})")
|
||||
|
||||
if not result.is_partial:
|
||||
# Final result
|
||||
for alt in result.alternatives:
|
||||
text = alt.transcript.strip()
|
||||
if text:
|
||||
self.transcript_parts.append(text)
|
||||
logger.bind(tag=TAG).debug(f"Final transcript part: {text}")
|
||||
else:
|
||||
# Partial result (for real-time feedback)
|
||||
for alt in result.alternatives:
|
||||
text = alt.transcript.strip()
|
||||
if text:
|
||||
logger.bind(tag=TAG).debug(f"Partial transcript: {text}")
|
||||
|
||||
# Combine all final parts
|
||||
if self.transcript_parts:
|
||||
self.final_transcript = " ".join(self.transcript_parts)
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error handling transcript event: {e}")
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
"""
|
||||
Amazon Transcribe Real-time Streaming ASR Provider
|
||||
Uses Amazon Transcribe Streaming for true real-time speech recognition
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__(config)
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
|
||||
# AWS Configuration
|
||||
self.aws_access_key_id = config.get("aws_access_key_id")
|
||||
self.aws_secret_access_key = config.get("aws_secret_access_key")
|
||||
self.aws_region = config.get("aws_region", "us-east-1")
|
||||
|
||||
# Multi-language Configuration for India
|
||||
self.language_code = config.get("language_code", "en-IN")
|
||||
self.sample_rate = int(config.get("sample_rate", 16000))
|
||||
self.media_encoding = "pcm" # Fixed for streaming
|
||||
|
||||
# Indian languages supported by Amazon Transcribe
|
||||
self.supported_indian_languages = {
|
||||
"hi-IN": "Hindi",
|
||||
"bn-IN": "Bengali",
|
||||
"te-IN": "Telugu",
|
||||
"ta-IN": "Tamil",
|
||||
"gu-IN": "Gujarati",
|
||||
"kn-IN": "Kannada",
|
||||
"ml-IN": "Malayalam",
|
||||
"mr-IN": "Marathi",
|
||||
"pa-IN": "Punjabi",
|
||||
"en-IN": "English (India)"
|
||||
}
|
||||
|
||||
# Multi-language detection settings - temporarily disabled due to API conflicts
|
||||
enable_lang_detect = config.get("enable_language_detection", False)
|
||||
self.enable_language_detection = enable_lang_detect if isinstance(enable_lang_detect, bool) else str(enable_lang_detect).lower() == "true"
|
||||
|
||||
romanized = config.get("romanized_output", True)
|
||||
self.romanized_output = romanized if isinstance(romanized, bool) else str(romanized).lower() == "true"
|
||||
|
||||
# File management
|
||||
self.output_dir = config.get("output_dir", "./audio_files")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# Timeout configuration (short for real-time)
|
||||
timeout = config.get("timeout", 10)
|
||||
self.timeout = int(timeout) if timeout else 10
|
||||
|
||||
# Test AWS credentials
|
||||
try:
|
||||
session = boto3.Session(
|
||||
aws_access_key_id=self.aws_access_key_id,
|
||||
aws_secret_access_key=self.aws_secret_access_key,
|
||||
region_name=self.aws_region
|
||||
)
|
||||
|
||||
# Test credentials
|
||||
sts_client = session.client('sts')
|
||||
sts_client.get_caller_identity()
|
||||
logger.bind(tag=TAG).info("AWS credentials verified successfully")
|
||||
|
||||
except NoCredentialsError:
|
||||
logger.bind(tag=TAG).error("AWS credentials not found")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to verify AWS credentials: {e}")
|
||||
raise
|
||||
|
||||
# Ensure output directory exists
|
||||
if not os.path.exists(self.output_dir):
|
||||
os.makedirs(self.output_dir)
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Real-time ASR initialized - Region: {self.aws_region}, "
|
||||
f"Language: {self.language_code}, Sample Rate: {self.sample_rate}"
|
||||
)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Convert speech data to text using Amazon Transcribe Streaming"""
|
||||
start_time = time.time()
|
||||
audio_file_path = None
|
||||
|
||||
try:
|
||||
# Decode Opus to PCM if needed
|
||||
if audio_format == "opus":
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
if not pcm_data:
|
||||
logger.bind(tag=TAG).error("Failed to decode Opus audio")
|
||||
return None, None
|
||||
else:
|
||||
pcm_data = opus_data
|
||||
|
||||
# Save audio to temporary file for logging
|
||||
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# Calculate audio length for logging
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
audio_length_seconds = len(combined_pcm_data) / (self.sample_rate * 2)
|
||||
|
||||
# Perform real-time streaming transcription
|
||||
result_text = await self._stream_transcribe(combined_pcm_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Real-time completed in {elapsed_time:.2f}s: {result_text}"
|
||||
)
|
||||
|
||||
# Log the transcript
|
||||
if result_text:
|
||||
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
|
||||
|
||||
return result_text, audio_file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
|
||||
)
|
||||
return None, audio_file_path
|
||||
|
||||
finally:
|
||||
# Clean up audio file if configured
|
||||
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
|
||||
try:
|
||||
os.remove(audio_file_path)
|
||||
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
|
||||
|
||||
async def _stream_transcribe(self, pcm_data: bytes) -> Optional[str]:
|
||||
"""Perform real-time streaming transcription with language detection"""
|
||||
try:
|
||||
# Create streaming client
|
||||
client = TranscribeStreamingClient(region=self.aws_region)
|
||||
|
||||
# Configure streaming parameters
|
||||
stream_params = {
|
||||
'media_sample_rate_hz': self.sample_rate,
|
||||
'media_encoding': self.media_encoding,
|
||||
}
|
||||
|
||||
# Use specific language for now (language detection has API conflicts)
|
||||
stream_params['language_code'] = self.language_code
|
||||
logger.bind(tag=TAG).info(f"Using specific language: {self.language_code}")
|
||||
|
||||
# Start streaming transcription
|
||||
stream = await client.start_stream_transcription(**stream_params)
|
||||
|
||||
# Create handler for the stream
|
||||
handler = MyEventHandler(stream.output_stream)
|
||||
|
||||
# Send audio in chunks
|
||||
await self._send_audio_chunks(stream, pcm_data)
|
||||
|
||||
# Process the stream
|
||||
await self._process_stream(stream, handler)
|
||||
|
||||
# Get the final transcript
|
||||
final_text = handler.final_transcript.strip()
|
||||
detected_language = getattr(handler, 'detected_language', self.language_code)
|
||||
|
||||
# Process romanized output if requested
|
||||
if final_text and self.romanized_output:
|
||||
final_text = await self._process_romanized_output(final_text, detected_language)
|
||||
|
||||
# Log detected language
|
||||
if detected_language and detected_language != self.language_code:
|
||||
language_name = self.supported_indian_languages.get(detected_language, detected_language)
|
||||
logger.bind(tag=TAG).info(f"Detected language: {language_name} ({detected_language})")
|
||||
|
||||
return final_text if final_text else None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Streaming transcription error: {e}")
|
||||
return None
|
||||
|
||||
async def _send_audio_chunks(self, stream, pcm_data: bytes):
|
||||
"""Send audio data in chunks to the streaming API"""
|
||||
try:
|
||||
chunk_size = 1024 * 4 # 4KB chunks
|
||||
|
||||
for i in range(0, len(pcm_data), chunk_size):
|
||||
chunk = pcm_data[i:i + chunk_size]
|
||||
await stream.input_stream.send_audio_event(audio_chunk=chunk)
|
||||
await asyncio.sleep(0.01) # Small delay for streaming
|
||||
|
||||
# End the audio stream
|
||||
await stream.input_stream.end_stream()
|
||||
logger.bind(tag=TAG).debug("Audio streaming completed")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error sending audio chunks: {e}")
|
||||
|
||||
async def _process_stream(self, stream, handler):
|
||||
"""Process the transcript stream"""
|
||||
try:
|
||||
# Process events with timeout
|
||||
async def process_events():
|
||||
async for event in stream.output_stream:
|
||||
await handler.handle_transcript_event(event)
|
||||
# Break if we have a complete transcript
|
||||
if handler.final_transcript:
|
||||
break
|
||||
|
||||
# Wait for processing with timeout
|
||||
await asyncio.wait_for(process_events(), timeout=self.timeout)
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
logger.bind(tag=TAG).warning(f"Stream processing timed out after {self.timeout}s")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error processing stream: {e}")
|
||||
|
||||
async def _process_romanized_output(self, text: str, language_code: str) -> str:
|
||||
"""Process text to ensure romanized output for Indian languages"""
|
||||
try:
|
||||
# Amazon Transcribe already provides romanized output for Indian languages
|
||||
# But we can add additional processing if needed
|
||||
|
||||
language_name = self.supported_indian_languages.get(language_code, "Unknown")
|
||||
|
||||
# Log the language detected
|
||||
logger.bind(tag=TAG).info(f"Romanized {language_name} output: {text}")
|
||||
|
||||
# Add language indicator to the output if it's not English
|
||||
if language_code != "en-IN" and language_code in self.supported_indian_languages:
|
||||
# Optionally prefix with language indicator
|
||||
# return f"[{language_name}] {text}"
|
||||
return text # Return as-is since Amazon Transcribe provides romanized output
|
||||
|
||||
return text
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error processing romanized output: {e}")
|
||||
return text
|
||||
|
||||
async def _simple_chunk_transcribe(self, pcm_data: bytes) -> Optional[str]:
|
||||
"""Fallback: Simple chunked approach for better reliability"""
|
||||
try:
|
||||
# This is a more reliable approach that processes smaller chunks
|
||||
# and combines results, mimicking real-time performance
|
||||
|
||||
chunk_size = len(pcm_data) // 3 # Split into 3 parts
|
||||
if chunk_size < 1600: # Minimum chunk size
|
||||
chunk_size = len(pcm_data)
|
||||
|
||||
results = []
|
||||
|
||||
for i in range(0, len(pcm_data), chunk_size):
|
||||
chunk = pcm_data[i:i + chunk_size]
|
||||
if len(chunk) < 800: # Skip very small chunks
|
||||
continue
|
||||
|
||||
# Process chunk (simplified for reliability)
|
||||
# In a full implementation, you'd send each chunk to streaming API
|
||||
await asyncio.sleep(0.1) # Simulate processing time
|
||||
|
||||
# For now, return a simple acknowledgment that we received audio
|
||||
# This can be enhanced with actual streaming implementation
|
||||
if len(pcm_data) > 1600:
|
||||
return "I heard you speaking" # Placeholder until full streaming is implemented
|
||||
else:
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Simple chunk transcribe error: {e}")
|
||||
return None
|
||||
|
|
@ -0,0 +1,247 @@
|
|||
import os
|
||||
import time
|
||||
import asyncio
|
||||
import boto3
|
||||
import json
|
||||
from amazon_transcribe.client import TranscribeStreamingClient
|
||||
from amazon_transcribe.handlers import TranscriptResultStreamHandler
|
||||
from amazon_transcribe.model import TranscriptEvent
|
||||
from botocore.exceptions import ClientError, NoCredentialsError
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class TranscriptEventHandler(TranscriptResultStreamHandler):
|
||||
"""Handler for Amazon Transcribe streaming events"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.transcript_text = ""
|
||||
self.is_final = False
|
||||
self.completed = False
|
||||
|
||||
async def handle_transcript_event(self, transcript_event: TranscriptEvent):
|
||||
results = transcript_event.transcript.results
|
||||
for result in results:
|
||||
if result.is_partial:
|
||||
# Handle partial results for real-time feedback
|
||||
for alt in result.alternatives:
|
||||
logger.bind(tag=TAG).debug(f"Partial transcript: {alt.transcript}")
|
||||
else:
|
||||
# Handle final results
|
||||
for alt in result.alternatives:
|
||||
self.transcript_text += alt.transcript + " "
|
||||
logger.bind(tag=TAG).debug(f"Final transcript: {alt.transcript}")
|
||||
self.is_final = True
|
||||
|
||||
# Check if stream is complete
|
||||
if not results:
|
||||
self.completed = True
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
"""
|
||||
Amazon Transcribe Streaming ASR Provider
|
||||
Uses Amazon Transcribe Streaming service for real-time speech-to-text
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__(config)
|
||||
self.interface_type = InterfaceType.NON_STREAM # Keep as non-stream for compatibility
|
||||
|
||||
# AWS Configuration
|
||||
self.aws_access_key_id = config.get("aws_access_key_id")
|
||||
self.aws_secret_access_key = config.get("aws_secret_access_key")
|
||||
self.aws_region = config.get("aws_region", "us-east-1")
|
||||
|
||||
# Transcription Configuration
|
||||
self.language_code = config.get("language_code", "en-US")
|
||||
self.sample_rate = int(config.get("sample_rate", 16000))
|
||||
self.media_encoding = config.get("media_encoding", "pcm")
|
||||
|
||||
# File management
|
||||
self.output_dir = config.get("output_dir", "./audio_files")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# Timeout configuration
|
||||
timeout = config.get("timeout", 30)
|
||||
self.timeout = int(timeout) if timeout else 30
|
||||
|
||||
# Initialize AWS session
|
||||
try:
|
||||
self.session = boto3.Session(
|
||||
aws_access_key_id=self.aws_access_key_id,
|
||||
aws_secret_access_key=self.aws_secret_access_key,
|
||||
region_name=self.aws_region
|
||||
)
|
||||
|
||||
# Test credentials
|
||||
sts_client = self.session.client('sts')
|
||||
sts_client.get_caller_identity()
|
||||
|
||||
except NoCredentialsError:
|
||||
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to initialize AWS session: {e}")
|
||||
raise
|
||||
|
||||
# Ensure output directory exists
|
||||
if not os.path.exists(self.output_dir):
|
||||
os.makedirs(self.output_dir)
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Streaming ASR initialized - Region: {self.aws_region}, "
|
||||
f"Language: {self.language_code}, Sample Rate: {self.sample_rate}"
|
||||
)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Convert speech data to text using Amazon Transcribe Streaming"""
|
||||
start_time = time.time()
|
||||
audio_file_path = None
|
||||
|
||||
try:
|
||||
# Decode Opus to PCM if needed
|
||||
if audio_format == "opus":
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
if not pcm_data:
|
||||
logger.bind(tag=TAG).error("Failed to decode Opus audio")
|
||||
return None, None
|
||||
else:
|
||||
pcm_data = opus_data
|
||||
|
||||
# Save audio to temporary file for debugging/logging
|
||||
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# Calculate audio length for logging
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
audio_length_seconds = len(combined_pcm_data) / (self.sample_rate * 2) # 16-bit audio
|
||||
|
||||
# Perform streaming transcription
|
||||
result_text = await self._stream_transcribe(combined_pcm_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Streaming completed in {elapsed_time:.2f}s: {result_text}"
|
||||
)
|
||||
|
||||
# Log the transcript for debugging/analysis
|
||||
if result_text:
|
||||
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
|
||||
|
||||
return result_text, audio_file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
|
||||
)
|
||||
return None, audio_file_path
|
||||
|
||||
finally:
|
||||
# Clean up audio file if configured
|
||||
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
|
||||
try:
|
||||
os.remove(audio_file_path)
|
||||
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
|
||||
|
||||
async def _stream_transcribe(self, pcm_data: bytes) -> Optional[str]:
|
||||
"""Perform streaming transcription"""
|
||||
try:
|
||||
# Create streaming client
|
||||
client = TranscribeStreamingClient(region=self.aws_region)
|
||||
|
||||
# Create event handler
|
||||
handler = TranscriptEventHandler()
|
||||
|
||||
# Create audio stream generator
|
||||
async def audio_generator():
|
||||
# Split audio into chunks for streaming
|
||||
chunk_size = 1024 * 8 # 8KB chunks
|
||||
for i in range(0, len(pcm_data), chunk_size):
|
||||
chunk = pcm_data[i:i + chunk_size]
|
||||
yield {"AudioEvent": {"AudioChunk": chunk}}
|
||||
await asyncio.sleep(0.01) # Small delay to simulate streaming
|
||||
|
||||
# Start streaming transcription
|
||||
stream = await client.start_stream_transcription(
|
||||
language_code=self.language_code,
|
||||
media_sample_rate_hz=self.sample_rate,
|
||||
media_encoding=self.media_encoding,
|
||||
)
|
||||
|
||||
# Set up the event handler
|
||||
async def handle_stream():
|
||||
async for event in stream.output_stream:
|
||||
await handler.handle_transcript_event(event)
|
||||
if handler.completed:
|
||||
break
|
||||
|
||||
# Send audio and handle responses concurrently
|
||||
tasks = [
|
||||
asyncio.create_task(stream.input_stream.send_audio_event(audio_generator())),
|
||||
asyncio.create_task(handle_stream())
|
||||
]
|
||||
|
||||
# Wait for completion with timeout
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(*tasks, return_exceptions=True),
|
||||
timeout=self.timeout
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.bind(tag=TAG).warning(f"Streaming transcription timed out after {self.timeout}s")
|
||||
return None
|
||||
|
||||
# End the stream
|
||||
await stream.input_stream.end_stream()
|
||||
|
||||
# Return the final transcript
|
||||
final_text = handler.transcript_text.strip()
|
||||
return final_text if final_text else None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Streaming transcription error: {e}")
|
||||
return None
|
||||
|
||||
async def _simple_transcribe(self, pcm_data: bytes) -> Optional[str]:
|
||||
"""Fallback: Simple in-memory transcription without actual streaming"""
|
||||
try:
|
||||
# This is a simplified approach that processes the entire audio at once
|
||||
# but uses the streaming client for better performance than file-based
|
||||
|
||||
client = TranscribeStreamingClient(region=self.aws_region)
|
||||
|
||||
# Create a simple audio event
|
||||
audio_event = {
|
||||
"AudioEvent": {
|
||||
"AudioChunk": pcm_data
|
||||
}
|
||||
}
|
||||
|
||||
# For now, let's use a simpler approach
|
||||
# In a real implementation, you'd want proper streaming
|
||||
# But this gives us the performance benefits without the complexity
|
||||
|
||||
# Simulate processing time (much faster than file-based)
|
||||
await asyncio.sleep(0.5) # Much faster than 26 seconds!
|
||||
|
||||
# Return a placeholder - in reality you'd implement proper streaming
|
||||
# For now, let's fall back to a simple mock for testing
|
||||
logger.bind(tag=TAG).info("Using simplified streaming transcription")
|
||||
|
||||
# This is where you'd implement the actual streaming logic
|
||||
# For now, return None to indicate we need the full implementation
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Simple transcription error: {e}")
|
||||
return None
|
||||
|
|
@ -0,0 +1,254 @@
|
|||
import os
|
||||
import time
|
||||
import asyncio
|
||||
import boto3
|
||||
import tempfile
|
||||
import uuid
|
||||
from botocore.exceptions import ClientError, NoCredentialsError
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
"""
|
||||
Amazon Transcribe Streaming ASR Provider (Simplified)
|
||||
Uses a simplified approach for faster transcription than file-based
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__(config)
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
|
||||
# AWS Configuration
|
||||
self.aws_access_key_id = config.get("aws_access_key_id")
|
||||
self.aws_secret_access_key = config.get("aws_secret_access_key")
|
||||
self.aws_region = config.get("aws_region", "us-east-1")
|
||||
|
||||
# Transcription Configuration
|
||||
self.language_code = config.get("language_code", "en-US")
|
||||
self.sample_rate = int(config.get("sample_rate", 16000))
|
||||
|
||||
# File management
|
||||
self.output_dir = config.get("output_dir", "./audio_files")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# Timeout configuration (much shorter for streaming)
|
||||
timeout = config.get("timeout", 10)
|
||||
self.timeout = int(timeout) if timeout else 10
|
||||
|
||||
# Initialize AWS clients
|
||||
try:
|
||||
session = boto3.Session(
|
||||
aws_access_key_id=self.aws_access_key_id,
|
||||
aws_secret_access_key=self.aws_secret_access_key,
|
||||
region_name=self.aws_region
|
||||
)
|
||||
|
||||
# Test credentials
|
||||
sts_client = session.client('sts')
|
||||
sts_client.get_caller_identity()
|
||||
|
||||
# Create transcribe client for potential future streaming
|
||||
self.transcribe_client = session.client('transcribe')
|
||||
|
||||
except NoCredentialsError:
|
||||
logger.bind(tag=TAG).error("AWS credentials not found. Please configure aws_access_key_id and aws_secret_access_key")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to initialize AWS clients: {e}")
|
||||
raise
|
||||
|
||||
# Ensure output directory exists
|
||||
if not os.path.exists(self.output_dir):
|
||||
os.makedirs(self.output_dir)
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Streaming ASR initialized - Region: {self.aws_region}, "
|
||||
f"Language: {self.language_code}, Timeout: {self.timeout}s"
|
||||
)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Convert speech data to text using simplified streaming approach"""
|
||||
start_time = time.time()
|
||||
audio_file_path = None
|
||||
|
||||
try:
|
||||
# Decode Opus to PCM if needed
|
||||
if audio_format == "opus":
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
if not pcm_data:
|
||||
logger.bind(tag=TAG).error("Failed to decode Opus audio")
|
||||
return None, None
|
||||
else:
|
||||
pcm_data = opus_data
|
||||
|
||||
# Save audio to temporary file
|
||||
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# Calculate audio length for logging
|
||||
audio_length_seconds = len(b"".join(pcm_data)) / (self.sample_rate * 2) # 16-bit audio
|
||||
|
||||
# Perform fast transcription (simulate streaming performance)
|
||||
result_text = await self._fast_transcribe(pcm_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Amazon Transcribe Streaming completed in {elapsed_time:.2f}s: {result_text}"
|
||||
)
|
||||
|
||||
# Log the transcript for debugging/analysis
|
||||
if result_text:
|
||||
self.log_audio_transcript(audio_file_path, audio_length_seconds, result_text)
|
||||
|
||||
return result_text, audio_file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
|
||||
)
|
||||
return None, audio_file_path
|
||||
|
||||
finally:
|
||||
# Clean up audio file if configured
|
||||
if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path):
|
||||
try:
|
||||
os.remove(audio_file_path)
|
||||
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"Failed to delete audio file {audio_file_path}: {e}")
|
||||
|
||||
async def _fast_transcribe(self, pcm_data: List[bytes]) -> Optional[str]:
|
||||
"""Real Amazon Transcribe using start_transcription_job but optimized"""
|
||||
try:
|
||||
# Create temporary file for transcription
|
||||
combined_data = b"".join(pcm_data)
|
||||
|
||||
# Create temporary WAV file in memory-like approach
|
||||
temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
|
||||
|
||||
try:
|
||||
# Write WAV header and data
|
||||
import wave
|
||||
with wave.open(temp_file.name, 'wb') as wav_file:
|
||||
wav_file.setnchannels(1) # Mono
|
||||
wav_file.setsampwidth(2) # 16-bit
|
||||
wav_file.setframerate(self.sample_rate) # Sample rate
|
||||
wav_file.writeframes(combined_data)
|
||||
|
||||
# Use start_transcription_job for real transcription
|
||||
job_name = f"xiaozhi-stream-{uuid.uuid4().hex[:8]}-{int(time.time())}"
|
||||
|
||||
# Upload to S3 first (required for Transcribe)
|
||||
# But use a much more optimized approach
|
||||
import boto3
|
||||
s3_client = boto3.client(
|
||||
's3',
|
||||
aws_access_key_id=self.aws_access_key_id,
|
||||
aws_secret_access_key=self.aws_secret_access_key,
|
||||
region_name=self.aws_region
|
||||
)
|
||||
|
||||
# Create a temporary bucket key
|
||||
s3_key = f"temp-audio/{job_name}.wav"
|
||||
s3_bucket = "cheeko-audio-files" # Use existing bucket
|
||||
|
||||
# Quick upload
|
||||
s3_client.upload_file(temp_file.name, s3_bucket, s3_key)
|
||||
|
||||
# Start transcription job
|
||||
response = self.transcribe_client.start_transcription_job(
|
||||
TranscriptionJobName=job_name,
|
||||
Media={'MediaFileUri': f's3://{s3_bucket}/{s3_key}'},
|
||||
MediaFormat='wav',
|
||||
LanguageCode=self.language_code,
|
||||
MediaSampleRateHertz=self.sample_rate
|
||||
)
|
||||
|
||||
# Poll for completion (optimized for speed)
|
||||
max_attempts = self.timeout # Use timeout as max attempts (1 per second)
|
||||
for attempt in range(max_attempts):
|
||||
await asyncio.sleep(1) # Wait 1 second between checks
|
||||
|
||||
job_response = self.transcribe_client.get_transcription_job(
|
||||
TranscriptionJobName=job_name
|
||||
)
|
||||
|
||||
status = job_response['TranscriptionJob']['TranscriptionJobStatus']
|
||||
|
||||
if status == 'COMPLETED':
|
||||
# Get transcript
|
||||
transcript_uri = job_response['TranscriptionJob']['Transcript']['TranscriptFileUri']
|
||||
|
||||
# Download and parse transcript
|
||||
import urllib.request
|
||||
import json
|
||||
|
||||
response = urllib.request.urlopen(transcript_uri)
|
||||
transcript_data = json.loads(response.read().decode('utf-8'))
|
||||
|
||||
# Extract text
|
||||
results = transcript_data.get('results', {})
|
||||
transcripts = results.get('transcripts', [])
|
||||
|
||||
if transcripts and len(transcripts) > 0:
|
||||
final_text = transcripts[0].get('transcript', '')
|
||||
|
||||
# Cleanup job and S3 object
|
||||
try:
|
||||
self.transcribe_client.delete_transcription_job(
|
||||
TranscriptionJobName=job_name
|
||||
)
|
||||
s3_client.delete_object(Bucket=s3_bucket, Key=s3_key)
|
||||
except:
|
||||
pass # Ignore cleanup errors
|
||||
|
||||
return final_text
|
||||
else:
|
||||
return None
|
||||
|
||||
elif status == 'FAILED':
|
||||
failure_reason = job_response['TranscriptionJob'].get('FailureReason', 'Unknown error')
|
||||
logger.bind(tag=TAG).error(f"Transcription failed: {failure_reason}")
|
||||
return None
|
||||
|
||||
# Timeout
|
||||
logger.bind(tag=TAG).warning(f"Transcription timed out after {self.timeout} seconds")
|
||||
return None
|
||||
|
||||
finally:
|
||||
# Clean up temporary file
|
||||
try:
|
||||
os.unlink(temp_file.name)
|
||||
except:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Real transcription error: {e}")
|
||||
return None
|
||||
|
||||
async def _future_streaming_implementation(self, pcm_data: List[bytes]) -> Optional[str]:
|
||||
"""Placeholder for future true streaming implementation"""
|
||||
# This is where you would implement the actual Amazon Transcribe Streaming
|
||||
# For now, we're using the mock above to test the integration
|
||||
|
||||
try:
|
||||
# Future implementation would:
|
||||
# 1. Create TranscribeStreamingClient
|
||||
# 2. Set up audio stream
|
||||
# 3. Process results in real-time
|
||||
# 4. Return final transcript
|
||||
|
||||
# Placeholder implementation
|
||||
logger.bind(tag=TAG).debug("Future streaming implementation called")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Streaming implementation error: {e}")
|
||||
return None
|
||||
|
|
@ -62,6 +62,51 @@ class ASRProviderBase(ABC):
|
|||
else:
|
||||
have_voice = conn.client_have_voice
|
||||
|
||||
# Check for maximum recording timeout (default 10 seconds)
|
||||
# This applies when we're actively recording (have accumulated audio)
|
||||
recording_start_time = None
|
||||
if hasattr(conn, 'listen_start_time'):
|
||||
recording_start_time = conn.listen_start_time # Manual listen mode
|
||||
logger.bind(tag=TAG).debug(f"Using manual listen start time: {recording_start_time}")
|
||||
elif hasattr(conn, 'vad_recording_start_time'):
|
||||
recording_start_time = conn.vad_recording_start_time # Auto VAD mode
|
||||
logger.bind(tag=TAG).debug(f"Using VAD recording start time: {recording_start_time}")
|
||||
else:
|
||||
logger.bind(tag=TAG).debug("No recording start time found")
|
||||
|
||||
if len(conn.asr_audio) > 0 and recording_start_time and not conn.client_voice_stop:
|
||||
current_time = time.time()
|
||||
recording_duration = current_time - recording_start_time
|
||||
max_recording_time = conn.config.get('max_recording_time', 10.0)
|
||||
logger.bind(tag=TAG).debug(f"Recording duration: {recording_duration:.2f}s, max: {max_recording_time}s, audio chunks: {len(conn.asr_audio)}")
|
||||
if recording_duration >= max_recording_time:
|
||||
# Use a timeout flag to prevent multiple timeout messages
|
||||
if not hasattr(conn, '_timeout_triggered') or not conn._timeout_triggered:
|
||||
logger.bind(tag=TAG).info(f"Maximum recording time reached ({recording_duration:.2f}s) - forcing voice stop")
|
||||
conn._timeout_triggered = True
|
||||
|
||||
# Force voice stop using the same logic as VAD silence detection
|
||||
conn.client_voice_stop = True
|
||||
have_voice = False
|
||||
|
||||
# Process any accumulated audio before resetting (same as normal VAD flow)
|
||||
if len(conn.asr_audio) > 20:
|
||||
asr_audio_task = conn.asr_audio.copy()
|
||||
conn.asr_audio.clear()
|
||||
conn.reset_vad_states()
|
||||
conn._timeout_triggered = False # Reset for next session
|
||||
# Process the accumulated audio
|
||||
asyncio.create_task(self.handle_voice_stop(conn, asr_audio_task))
|
||||
else:
|
||||
# No significant audio to process, just reset everything
|
||||
conn.reset_vad_states()
|
||||
conn._timeout_triggered = False # Reset for next session
|
||||
|
||||
return # Exit early like VAD does
|
||||
else:
|
||||
# Already triggered timeout, skip this audio chunk
|
||||
return
|
||||
|
||||
# Debug logging
|
||||
if not hasattr(conn, '_asr_log_counter'):
|
||||
conn._asr_log_counter = 0
|
||||
|
|
@ -88,6 +133,10 @@ class ASRProviderBase(ABC):
|
|||
# Clear the just_started_listening flag when actual voice is detected
|
||||
if hasattr(conn, 'just_started_listening'):
|
||||
conn.just_started_listening = False
|
||||
# Start recording timer for VAD-based sessions
|
||||
if not hasattr(conn, 'vad_recording_start_time'):
|
||||
conn.vad_recording_start_time = time.time()
|
||||
logger.bind(tag=TAG).debug("VAD recording session started")
|
||||
# Add pre-buffered audio to the beginning of ASR audio
|
||||
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
|
||||
conn.audio_pre_buffer.clear()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import traceback
|
||||
import time
|
||||
import asyncio
|
||||
from ..base import MemoryProviderBase, logger
|
||||
from mem0 import MemoryClient
|
||||
from core.utils.util import check_model_key
|
||||
|
|
@ -9,56 +11,97 @@ TAG = __name__
|
|||
class MemoryProvider(MemoryProviderBase):
|
||||
def __init__(self, config, summary_memory=None):
|
||||
super().__init__(config)
|
||||
logger.bind(tag=TAG).info("[MEM0-INIT] Initializing MEM0 memory provider")
|
||||
logger.bind(tag=TAG).info(f"[MEM0-INIT] Config received: {config}")
|
||||
|
||||
self.api_key = config.get("api_key", "")
|
||||
self.api_version = config.get("api_version", "v1.1")
|
||||
|
||||
# Debug logging for API key (show first/last 4 chars only for security)
|
||||
if self.api_key:
|
||||
masked_key = f"{self.api_key[:4]}...{self.api_key[-4:]}" if len(self.api_key) > 8 else "****"
|
||||
logger.bind(tag=TAG).info(f"[MEM0-INIT] API key configured: {masked_key} (length: {len(self.api_key)})")
|
||||
else:
|
||||
logger.bind(tag=TAG).error("[MEM0-INIT] API key is empty or not configured - MEM0 will be disabled")
|
||||
|
||||
model_key_msg = check_model_key("Mem0ai", self.api_key)
|
||||
if model_key_msg:
|
||||
logger.bind(tag=TAG).error(model_key_msg)
|
||||
logger.bind(tag=TAG).error(f"[MEM0-INIT] {model_key_msg}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0-INIT] API key validation failed. Please check your Mem0 API key configuration.")
|
||||
self.use_mem0 = False
|
||||
return
|
||||
else:
|
||||
self.use_mem0 = True
|
||||
logger.bind(tag=TAG).info("[MEM0-INIT] API key passed initial validation")
|
||||
|
||||
try:
|
||||
logger.bind(tag=TAG).info(f"[MEM0-INIT] Attempting to connect to Mem0ai service with API version: {self.api_version}")
|
||||
self.client = MemoryClient(api_key=self.api_key)
|
||||
logger.bind(tag=TAG).info(
|
||||
"Successfully connected to Mem0ai service")
|
||||
"[MEM0-INIT] Successfully connected to Mem0ai service - MEM0 is ENABLED")
|
||||
logger.bind(tag=TAG).info(f"[MEM0-INIT] role_id/user_id: {self.role_id}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Error occurred while connecting to Mem0ai service: {str(e)}")
|
||||
f"[MEM0-INIT] Error occurred while connecting to Mem0ai service: {str(e)}")
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Detailed error: {traceback.format_exc()}")
|
||||
f"[MEM0-INIT] Detailed error: {traceback.format_exc()}")
|
||||
logger.bind(tag=TAG).error(
|
||||
"[MEM0-INIT] Please verify your API key at https://app.mem0.ai/dashboard/api-keys")
|
||||
self.use_mem0 = False
|
||||
|
||||
async def save_memory(self, msgs):
|
||||
logger.bind(tag=TAG).info(f"[MEM0] save_memory called with {len(msgs) if msgs else 0} messages")
|
||||
|
||||
if not self.use_mem0:
|
||||
logger.bind(tag=TAG).warning("[MEM0] Memory saving skipped - use_mem0 is False")
|
||||
return None
|
||||
if len(msgs) < 2:
|
||||
logger.bind(tag=TAG).info(f"[MEM0] Memory saving skipped - insufficient messages (got {len(msgs)}, need at least 2)")
|
||||
return None
|
||||
|
||||
try:
|
||||
logger.bind(tag=TAG).info(f"[MEM0] Preparing to save memory for user_id: {self.role_id}")
|
||||
|
||||
# Format the content as a message list for mem0
|
||||
messages = [
|
||||
{"role": message.role, "content": message.content}
|
||||
for message in msgs
|
||||
if message.role != "system"
|
||||
]
|
||||
|
||||
logger.bind(tag=TAG).info(f"[MEM0] Formatted {len(messages)} messages for saving (excluded system messages)")
|
||||
logger.bind(tag=TAG).debug(f"[MEM0] Messages to save: {messages[:2]}...") # Log first 2 messages for debugging
|
||||
|
||||
logger.bind(tag=TAG).info(f"[MEM0] Calling client.add() with API version: {self.api_version}")
|
||||
result = self.client.add(
|
||||
messages, user_id=self.role_id, output_format=self.api_version
|
||||
)
|
||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||
|
||||
logger.bind(tag=TAG).info(f"[MEM0] Memory saved successfully! Result: {result}")
|
||||
logger.bind(tag=TAG).debug(f"[MEM0] Full save memory result: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to save memory: {str(e)}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0] Failed to save memory: {str(e)}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0] Exception type: {type(e).__name__}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0] Full traceback: {traceback.format_exc()}")
|
||||
return None
|
||||
|
||||
async def query_memory(self, query: str) -> str:
|
||||
logger.bind(tag=TAG).info(f"[MEM0-QUERY] query_memory called with query: {query[:100]}...")
|
||||
|
||||
if not self.use_mem0:
|
||||
logger.bind(tag=TAG).warning("[MEM0-QUERY] Query skipped - use_mem0 is False")
|
||||
return ""
|
||||
try:
|
||||
logger.bind(tag=TAG).info(f"[MEM0-QUERY] Searching memories for user_id: {self.role_id}")
|
||||
results = self.client.search(
|
||||
query, user_id=self.role_id, output_format=self.api_version
|
||||
)
|
||||
|
||||
# logger.bind(tag=TAG).info(f"[MEM0-QUERY] Search completed. Results: {results}")
|
||||
|
||||
if not results or "results" not in results:
|
||||
logger.bind(tag=TAG).info("[MEM0-QUERY] No results found or invalid response format")
|
||||
return ""
|
||||
|
||||
# Format each memory entry with its update time up to minutes
|
||||
|
|
@ -83,8 +126,46 @@ class MemoryProvider(MemoryProviderBase):
|
|||
|
||||
# Extract only the formatted strings
|
||||
memories_str = "\n".join(f"- {memory[1]}" for memory in memories)
|
||||
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
|
||||
logger.bind(tag=TAG).info(f"[MEM0-QUERY] Found {len(memories)} memories")
|
||||
logger.bind(tag=TAG).debug(f"[MEM0-QUERY] Query results: {memories_str}")
|
||||
return memories_str
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to query memory: {str(e)}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0-QUERY] Failed to query memory: {str(e)}")
|
||||
logger.bind(tag=TAG).error(f"[MEM0-QUERY] Exception traceback: {traceback.format_exc()}")
|
||||
return ""
|
||||
|
||||
async def test_mem0_connection(self):
|
||||
"""Test MEM0 connection and verify saving/retrieval works"""
|
||||
logger.bind(tag=TAG).info("[MEM0-TEST] Testing MEM0 connection and functionality")
|
||||
|
||||
if not self.use_mem0:
|
||||
logger.bind(tag=TAG).error("[MEM0-TEST] MEM0 is disabled (use_mem0=False)")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Test saving a simple message
|
||||
test_msg = f"Test message at {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
logger.bind(tag=TAG).info(f"[MEM0-TEST] Saving test message: {test_msg}")
|
||||
|
||||
test_result = self.client.add(
|
||||
test_msg,
|
||||
user_id=self.role_id,
|
||||
output_format=self.api_version
|
||||
)
|
||||
logger.bind(tag=TAG).info(f"[MEM0-TEST] Test save result: {test_result}")
|
||||
|
||||
# Try to retrieve it immediately
|
||||
await asyncio.sleep(2) # Give MEM0 2 seconds to process
|
||||
|
||||
logger.bind(tag=TAG).info("[MEM0-TEST] Retrieving test message")
|
||||
search_result = self.client.search(
|
||||
"test message",
|
||||
user_id=self.role_id,
|
||||
output_format=self.api_version
|
||||
)
|
||||
logger.bind(tag=TAG).info(f"[MEM0-TEST] Test search result: {search_result}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"[MEM0-TEST] Test failed: {str(e)}")
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -13,11 +13,48 @@ logger = setup_logging()
|
|||
|
||||
def create_instance(class_name, *args, **kwargs):
|
||||
# Create LLM instance
|
||||
if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')):
|
||||
|
||||
# Try relative path first (original behavior)
|
||||
provider_path = os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')
|
||||
|
||||
# If relative path doesn't work, try absolute path from project root
|
||||
if not os.path.exists(provider_path):
|
||||
provider_path = os.path.join(project_root, 'core', 'providers', 'llm', class_name, f'{class_name}.py')
|
||||
|
||||
# Debug logging
|
||||
logger.bind(tag=__name__).info(f"Looking for LLM provider: {class_name}")
|
||||
logger.bind(tag=__name__).info(f"Current working directory: {os.getcwd()}")
|
||||
logger.bind(tag=__name__).info(f"Project root: {project_root}")
|
||||
logger.bind(tag=__name__).info(f"Provider path: {provider_path}")
|
||||
logger.bind(tag=__name__).info(f"Provider exists: {os.path.exists(provider_path)}")
|
||||
|
||||
if os.path.exists(provider_path):
|
||||
lib_name = f'core.providers.llm.{class_name}.{class_name}'
|
||||
logger.bind(tag=__name__).info(f"Loading module: {lib_name}")
|
||||
|
||||
if lib_name not in sys.modules:
|
||||
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
|
||||
try:
|
||||
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
|
||||
logger.bind(tag=__name__).info(f"Successfully imported: {lib_name}")
|
||||
except ImportError as e:
|
||||
logger.bind(tag=__name__).error(f"Failed to import {lib_name}: {e}")
|
||||
raise ValueError(f"Failed to import LLM provider {class_name}: {e}")
|
||||
|
||||
return sys.modules[lib_name].LLMProvider(*args, **kwargs)
|
||||
|
||||
raise ValueError(
|
||||
f"Unsupported LLM type: {class_name}, please check if the type in this configuration is set correctly")
|
||||
|
||||
# Enhanced error message with debugging info
|
||||
cwd = os.getcwd()
|
||||
available_providers = []
|
||||
llm_dir = os.path.join(project_root, 'core', 'providers', 'llm')
|
||||
if os.path.exists(llm_dir):
|
||||
available_providers = [d for d in os.listdir(llm_dir)
|
||||
if os.path.isdir(os.path.join(llm_dir, d)) and d != '__pycache__']
|
||||
|
||||
error_msg = (f"Unsupported LLM type: {class_name}\n"
|
||||
f"Current working directory: {cwd}\n"
|
||||
f"Project root: {project_root}\n"
|
||||
f"Searched path: {provider_path}\n"
|
||||
f"Available providers: {available_providers}")
|
||||
|
||||
logger.bind(tag=__name__).error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
|
|
|||
|
|
@ -73,6 +73,20 @@ def initialize_modules(
|
|||
if "type" not in config["Memory"][select_memory_module]
|
||||
else config["Memory"][select_memory_module]["type"]
|
||||
)
|
||||
|
||||
# Debug logging for memory configuration
|
||||
memory_config = config["Memory"][select_memory_module]
|
||||
logger.bind(tag=TAG).debug(f"Memory module selected: {select_memory_module}")
|
||||
logger.bind(tag=TAG).debug(f"Memory type: {memory_type}")
|
||||
logger.bind(tag=TAG).debug(f"Memory config keys: {list(memory_config.keys()) if isinstance(memory_config, dict) else 'Not a dict'}")
|
||||
|
||||
if memory_type == "mem0ai" and isinstance(memory_config, dict):
|
||||
api_key = memory_config.get("api_key", "")
|
||||
if api_key:
|
||||
masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
|
||||
logger.bind(tag=TAG).debug(f"Mem0 API key from config: {masked_key} (length: {len(api_key)})")
|
||||
else:
|
||||
logger.bind(tag=TAG).warning("Mem0 API key not found in configuration")
|
||||
|
||||
modules["memory"] = memory.create_instance(
|
||||
memory_type,
|
||||
|
|
|
|||
63
main/xiaozhi-server/debug_llm_loading.py
Normal file
63
main/xiaozhi-server/debug_llm_loading.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug script to check LLM provider loading
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
def debug_llm_loading():
|
||||
"""Debug the LLM loading mechanism"""
|
||||
print("=== LLM Loading Debug ===")
|
||||
|
||||
# Check current working directory
|
||||
cwd = os.getcwd()
|
||||
print(f"Current working directory: {cwd}")
|
||||
|
||||
# Check the path that the code is looking for
|
||||
class_name = "openai"
|
||||
provider_path = os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')
|
||||
absolute_provider_path = os.path.abspath(provider_path)
|
||||
|
||||
print(f"Looking for provider at: {provider_path}")
|
||||
print(f"Absolute path: {absolute_provider_path}")
|
||||
print(f"Path exists: {os.path.exists(provider_path)}")
|
||||
|
||||
# Check if the core directory exists
|
||||
core_path = os.path.join('core')
|
||||
print(f"Core directory exists: {os.path.exists(core_path)}")
|
||||
|
||||
if os.path.exists(core_path):
|
||||
providers_path = os.path.join('core', 'providers')
|
||||
print(f"Providers directory exists: {os.path.exists(providers_path)}")
|
||||
|
||||
if os.path.exists(providers_path):
|
||||
llm_path = os.path.join('core', 'providers', 'llm')
|
||||
print(f"LLM directory exists: {os.path.exists(llm_path)}")
|
||||
|
||||
if os.path.exists(llm_path):
|
||||
openai_dir = os.path.join('core', 'providers', 'llm', 'openai')
|
||||
print(f"OpenAI directory exists: {os.path.exists(openai_dir)}")
|
||||
|
||||
if os.path.exists(openai_dir):
|
||||
openai_file = os.path.join('core', 'providers', 'llm', 'openai', 'openai.py')
|
||||
print(f"OpenAI file exists: {os.path.exists(openai_file)}")
|
||||
else:
|
||||
# List what's in the llm directory
|
||||
try:
|
||||
llm_contents = os.listdir(llm_path)
|
||||
print(f"Contents of {llm_path}: {llm_contents}")
|
||||
except Exception as e:
|
||||
print(f"Error listing {llm_path}: {e}")
|
||||
|
||||
# Check Python path
|
||||
print(f"Python path: {sys.path[:3]}...") # Show first 3 entries
|
||||
|
||||
# Try to see if we can import the module directly
|
||||
try:
|
||||
import core.providers.llm.openai.openai
|
||||
print("✅ Direct import of openai module successful")
|
||||
except ImportError as e:
|
||||
print(f"❌ Direct import failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
debug_llm_loading()
|
||||
70
main/xiaozhi-server/fix_database_config.py
Normal file
70
main/xiaozhi-server/fix_database_config.py
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to fix corrupted database configuration
|
||||
"""
|
||||
import json
|
||||
import httpx
|
||||
|
||||
# Configuration
|
||||
API_URL = "http://139.59.7.72:8002/toy"
|
||||
SECRET = "66122e75-3b2a-45d7-a082-0f0894529348"
|
||||
|
||||
def get_current_config():
|
||||
"""Get current configuration from database"""
|
||||
headers = {
|
||||
"Authorization": f"Bearer {SECRET}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
response = httpx.post(f"{API_URL}/config/server-base", headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()["data"]
|
||||
|
||||
def update_config(config_data):
|
||||
"""Update configuration in database"""
|
||||
headers = {
|
||||
"Authorization": f"Bearer {SECRET}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
# Assuming there's an update endpoint - we might need to find the correct one
|
||||
response = httpx.put(f"{API_URL}/config/server-base", headers=headers, json=config_data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def fix_config():
|
||||
"""Fix the corrupted configuration"""
|
||||
print("Getting current config...")
|
||||
config = get_current_config()
|
||||
|
||||
# Fix the corrupted log_level
|
||||
if "log" in config and config["log"].get("log_level") == "http://139.59.7.72:8002/toy/ota/":
|
||||
print("Fixing corrupted log_level...")
|
||||
config["log"]["log_level"] = "INFO"
|
||||
|
||||
# Ensure LLM configuration is correct (it seems to be already correct)
|
||||
if "LLM" in config and "Groq LLM" in config["LLM"]:
|
||||
llm_config = config["LLM"]["Groq LLM"]
|
||||
print(f"Current LLM config: {json.dumps(llm_config, indent=2)}")
|
||||
|
||||
# Add missing fields that might be needed
|
||||
llm_config.update({
|
||||
"timeout": 15,
|
||||
"max_retries": 2,
|
||||
"retry_delay": 1
|
||||
})
|
||||
|
||||
print("Fixed configuration:")
|
||||
print(json.dumps(config, indent=2))
|
||||
|
||||
# For now, just print the config to see what needs to be fixed
|
||||
# We'll need to find the correct update endpoint
|
||||
return config
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
fixed_config = fix_config()
|
||||
print("\nConfiguration has been analyzed. The main issue is the corrupted log_level.")
|
||||
print("You may need to use the admin interface to update this configuration.")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
55
main/xiaozhi-server/fix_log_config.py
Normal file
55
main/xiaozhi-server/fix_log_config.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to fix the corrupted log.log_level parameter
|
||||
"""
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
|
||||
# Database configuration
|
||||
DB_CONFIG = {
|
||||
'host': 'nozomi.proxy.rlwy.net',
|
||||
'port': 25037,
|
||||
'database': 'railway',
|
||||
'user': 'root',
|
||||
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm',
|
||||
'ssl_disabled': True,
|
||||
'use_unicode': True,
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def fix_log_level():
|
||||
"""Fix the corrupted log.log_level parameter"""
|
||||
connection = None
|
||||
try:
|
||||
connection = mysql.connector.connect(**DB_CONFIG)
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Check current value
|
||||
cursor.execute("SELECT param_value FROM sys_params WHERE param_code = 'log.log_level'")
|
||||
current_value = cursor.fetchone()
|
||||
print(f"Current log.log_level value: {current_value[0] if current_value else 'NOT FOUND'}")
|
||||
|
||||
# Fix the value
|
||||
cursor.execute(
|
||||
"UPDATE sys_params SET param_value = %s, update_date = NOW() WHERE param_code = %s",
|
||||
("INFO", "log.log_level")
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
# Verify the fix
|
||||
cursor.execute("SELECT param_value FROM sys_params WHERE param_code = 'log.log_level'")
|
||||
new_value = cursor.fetchone()
|
||||
print(f"Fixed log.log_level value: {new_value[0] if new_value else 'NOT FOUND'}")
|
||||
|
||||
print("SUCCESS: log.log_level has been fixed!")
|
||||
|
||||
except Error as e:
|
||||
print(f"Error: {e}")
|
||||
if connection:
|
||||
connection.rollback()
|
||||
finally:
|
||||
if connection and connection.is_connected():
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
fix_log_level()
|
||||
BIN
main/xiaozhi-server/music/English/Baa Baa Black Sheep.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Baa Baa Black Sheep.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Baby Shark Dance.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Baby Shark Dance.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Five Little Animals.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Five Little Animals.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Five Little Ducks.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Five Little Ducks.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Once I Caught A Fish Alive.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Once I Caught A Fish Alive.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Ten Little Dinos.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Ten Little Dinos.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/English/Wheels on the Bus Go.mp3
Normal file
BIN
main/xiaozhi-server/music/English/Wheels on the Bus Go.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/All is well.mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/All is well.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/Bandar Mama Aur Kele.mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/Bandar Mama Aur Kele.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/Bum Bum Bole.mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/Bum Bum Bole.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/Chidiya Rani Badi Sayani.mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/Chidiya Rani Badi Sayani.mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/Hanuman Chalisa .mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/Hanuman Chalisa .mp3
Normal file
Binary file not shown.
BIN
main/xiaozhi-server/music/Hindi/Happy New Year Song.mp3
Normal file
BIN
main/xiaozhi-server/music/Hindi/Happy New Year Song.mp3
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue