diff --git a/clear_redis.py b/clear_redis.py
index 65deaa529..79bbb67e8 100644
--- a/clear_redis.py
+++ b/clear_redis.py
@@ -2,12 +2,14 @@ import redis
# Redis connection configuration
redis_client = redis.Redis(
- host='maglev.proxy.rlwy.net',
- port=16780,
- password='beVfOKcZjMUCBiZIQnvSMivhpSeijpKP',
+ host='yamanote.proxy.rlwy.net',
+ port=34938,
+ password='YbdhwguVUNowduNpDZjuSefZFhBXiOEP',
username='default',
db=0,
- decode_responses=True
+ decode_responses=True,
+ socket_timeout=30,
+ socket_connect_timeout=30
)
try:
diff --git a/main/manager-api/README.md b/main/manager-api/README.md
index 92baacd92..e8822b8ea 100644
--- a/main/manager-api/README.md
+++ b/main/manager-api/README.md
@@ -2,16 +2,15 @@ This is a development document. If you need to deploy the Xiaozhi server, [click
# Project Introduction
-
run app
-
-npm run serve
+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.
# Development Environment
+
JDK 21
Maven 3.8+
MySQL 8.0+
@@ -19,9 +18,9 @@ Redis 5.0+
Vue 3.x
# API Documentation
+
After starting, open: http://localhost:8002/xiaozhi/doc.html
to run app
-
-mvn spring-boot:run
\ No newline at end of file
+mvn spring-boot:run
diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml
index e2b2ef16d..49ffdd655 100644
--- a/main/manager-api/pom.xml
+++ b/main/manager-api/pom.xml
@@ -32,6 +32,7 @@
4.20.0
4.1.0
3.4.0
+ 1.18.30
@@ -264,8 +265,15 @@
org.springframework.boot
spring-boot-maven-plugin
+ 3.4.3
xiaozhi.AdminApplication
+
+
+ org.projectlombok
+ lombok
+
+
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java b/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java
deleted file mode 100644
index 3c1c3a23b..000000000
--- a/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java
+++ /dev/null
@@ -1,505 +0,0 @@
-package xiaozhi.migration;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import com.google.gson.*;
-import com.google.gson.reflect.TypeToken;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.CommandLineRunner;
-import org.springframework.stereotype.Component;
-
-import xiaozhi.modules.content.dto.ContentLibraryDTO;
-import xiaozhi.modules.content.entity.ContentLibraryEntity;
-import xiaozhi.modules.content.service.ContentLibraryService;
-
-/**
- * Data Migration Script for Content Library
- *
- * This script migrates content metadata from JSON files in the xiaozhi-server directory
- * to the content_library database table.
- *
- * Usage: Run as a Spring Boot application with migration profile
- * java -jar app.jar --spring.profiles.active=migration
- *
- * Directory Structure:
- * - xiaozhi-server/music/[Language]/metadata.json (English, Hindi, Kannada, Phonics, Telugu)
- * - xiaozhi-server/stories/[Genre]/metadata.json (Adventure, Bedtime, Educational, Fairy Tales, Fantasy)
- *
- * @author Data Migration Script Generator
- * @version 1.0
- */
-@Slf4j
-@Component
-public class ContentLibraryMigration implements CommandLineRunner {
-
- @Autowired
- private ContentLibraryService contentLibraryService;
-
- private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- // Base path configuration - adjust as needed based on deployment structure
- private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
- private static final String MUSIC_PATH = BASE_PATH + "/music";
- private static final String STORIES_PATH = BASE_PATH + "/stories";
-
- // Batch size for database operations
- private static final int BATCH_SIZE = 100;
-
- // Migration statistics
- private final MigrationStatistics stats = new MigrationStatistics();
-
- @Override
- public void run(String... args) throws Exception {
- // Check if migration profile is active
- String profiles = System.getProperty("spring.profiles.active", "");
- if (!profiles.contains("migration")) {
- log.info("Migration profile not active, skipping content library migration");
- return;
- }
-
- log.info("Starting Content Library Migration...");
- log.info("Base path: {}", BASE_PATH);
-
- try {
- // Verify directory structure
- verifyDirectoryStructure();
-
- // Migrate music content
- migrateMusicContent();
-
- // Migrate story content
- migrateStoryContent();
-
- // Print migration summary
- printMigrationSummary();
-
- } catch (Exception e) {
- log.error("Migration failed: {}", e.getMessage(), e);
- throw new RuntimeException("Content library migration failed", e);
- }
- }
-
- /**
- * Verify that the required directory structure exists
- */
- private void verifyDirectoryStructure() {
- log.info("Verifying directory structure...");
-
- File baseDir = new File(BASE_PATH);
- if (!baseDir.exists()) {
- throw new RuntimeException("Base directory does not exist: " + BASE_PATH);
- }
-
- File musicDir = new File(MUSIC_PATH);
- if (!musicDir.exists()) {
- throw new RuntimeException("Music directory does not exist: " + MUSIC_PATH);
- }
-
- File storiesDir = new File(STORIES_PATH);
- if (!storiesDir.exists()) {
- throw new RuntimeException("Stories directory does not exist: " + STORIES_PATH);
- }
-
- log.info("Directory structure verified successfully");
- }
-
- /**
- * Migrate music content from JSON metadata files
- */
- private void migrateMusicContent() {
- log.info("Starting music content migration...");
-
- File musicDir = new File(MUSIC_PATH);
- File[] languageDirectories = musicDir.listFiles(File::isDirectory);
-
- if (languageDirectories == null || languageDirectories.length == 0) {
- log.warn("No music language directories found in: {}", MUSIC_PATH);
- return;
- }
-
- List allMusicContent = new ArrayList<>();
-
- for (File languageDir : languageDirectories) {
- String language = languageDir.getName();
- log.info("Processing music language: {}", language);
-
- try {
- List languageContent = processMusicLanguage(language, languageDir);
- allMusicContent.addAll(languageContent);
- stats.addProcessedLanguage(language, languageContent.size());
-
- } catch (Exception e) {
- log.error("Failed to process music language {}: {}", language, e.getMessage(), e);
- stats.addFailedLanguage(language, e.getMessage());
- }
- }
-
- // Batch insert music content
- if (!allMusicContent.isEmpty()) {
- batchInsertContent(allMusicContent, "music");
- }
-
- log.info("Completed music content migration. Processed {} items", allMusicContent.size());
- }
-
- /**
- * Process music content for a specific language
- */
- private List processMusicLanguage(String language, File languageDir) throws IOException {
- File metadataFile = new File(languageDir, "metadata.json");
- if (!metadataFile.exists()) {
- log.warn("No metadata.json found for language: {}", language);
- return new ArrayList<>();
- }
-
- String jsonContent = Files.readString(metadataFile.toPath());
-
- // Parse JSON content
- JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
- List contentList = new ArrayList<>();
-
- for (Map.Entry entry : jsonObject.entrySet()) {
- String title = entry.getKey();
- JsonObject contentInfo = entry.getValue().getAsJsonObject();
-
- try {
- ContentLibraryDTO dto = createMusicContentDTO(title, contentInfo, language);
- contentList.add(dto);
-
- } catch (Exception e) {
- log.error("Failed to process music item '{}' in language {}: {}", title, language, e.getMessage());
- stats.addFailedItem(title, e.getMessage());
- }
- }
-
- return contentList;
- }
-
- /**
- * Create ContentLibraryDTO for music content
- */
- private ContentLibraryDTO createMusicContentDTO(String title, JsonObject contentInfo, String language) {
- ContentLibraryDTO dto = new ContentLibraryDTO();
-
- // Basic information
- dto.setTitle(title);
- dto.setRomanized(getJsonString(contentInfo, "romanized"));
- dto.setFilename(getJsonString(contentInfo, "filename"));
- dto.setContentType(ContentLibraryEntity.ContentType.MUSIC.getValue());
- dto.setCategory(language);
-
- // Parse alternatives array
- JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
- if (alternativesArray != null) {
- List alternatives = new ArrayList<>();
- for (JsonElement element : alternativesArray) {
- alternatives.add(element.getAsString());
- }
- dto.setAlternatives(alternatives);
- } else {
- dto.setAlternatives(new ArrayList<>());
- }
-
- // Additional metadata (these might be null for now, can be populated later)
- dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
- dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
- dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
-
- // Set as active
- dto.setIsActive(true);
-
- return dto;
- }
-
- /**
- * Migrate story content from JSON metadata files
- */
- private void migrateStoryContent() {
- log.info("Starting story content migration...");
-
- File storiesDir = new File(STORIES_PATH);
- File[] genreDirectories = storiesDir.listFiles(File::isDirectory);
-
- if (genreDirectories == null || genreDirectories.length == 0) {
- log.warn("No story genre directories found in: {}", STORIES_PATH);
- return;
- }
-
- List allStoryContent = new ArrayList<>();
-
- for (File genreDir : genreDirectories) {
- String genre = genreDir.getName();
- log.info("Processing story genre: {}", genre);
-
- try {
- List genreContent = processStoryGenre(genre, genreDir);
- allStoryContent.addAll(genreContent);
- stats.addProcessedGenre(genre, genreContent.size());
-
- } catch (Exception e) {
- log.error("Failed to process story genre {}: {}", genre, e.getMessage(), e);
- stats.addFailedGenre(genre, e.getMessage());
- }
- }
-
- // Batch insert story content
- if (!allStoryContent.isEmpty()) {
- batchInsertContent(allStoryContent, "stories");
- }
-
- log.info("Completed story content migration. Processed {} items", allStoryContent.size());
- }
-
- /**
- * Process story content for a specific genre
- */
- private List processStoryGenre(String genre, File genreDir) throws IOException {
- File metadataFile = new File(genreDir, "metadata.json");
- if (!metadataFile.exists()) {
- log.warn("No metadata.json found for genre: {}", genre);
- return new ArrayList<>();
- }
-
- String jsonContent = Files.readString(metadataFile.toPath());
-
- // Parse JSON content
- JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
- List contentList = new ArrayList<>();
-
- for (Map.Entry entry : jsonObject.entrySet()) {
- String title = entry.getKey();
- JsonObject contentInfo = entry.getValue().getAsJsonObject();
-
- try {
- ContentLibraryDTO dto = createStoryContentDTO(title, contentInfo, genre);
- contentList.add(dto);
-
- } catch (Exception e) {
- log.error("Failed to process story item '{}' in genre {}: {}", title, genre, e.getMessage());
- stats.addFailedItem(title, e.getMessage());
- }
- }
-
- return contentList;
- }
-
- /**
- * Create ContentLibraryDTO for story content
- */
- private ContentLibraryDTO createStoryContentDTO(String title, JsonObject contentInfo, String genre) {
- ContentLibraryDTO dto = new ContentLibraryDTO();
-
- // Basic information
- dto.setTitle(title);
- dto.setRomanized(getJsonString(contentInfo, "romanized"));
- dto.setFilename(getJsonString(contentInfo, "filename"));
- dto.setContentType(ContentLibraryEntity.ContentType.STORY.getValue());
- dto.setCategory(genre);
-
- // Parse alternatives array
- JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
- if (alternativesArray != null) {
- List alternatives = new ArrayList<>();
- for (JsonElement element : alternativesArray) {
- alternatives.add(element.getAsString());
- }
- dto.setAlternatives(alternatives);
- } else {
- dto.setAlternatives(new ArrayList<>());
- }
-
- // Additional metadata (these might be null for now, can be populated later)
- dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
- dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
- dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
-
- // Set as active
- dto.setIsActive(true);
-
- return dto;
- }
-
- /**
- * Batch insert content into database
- */
- private void batchInsertContent(List contentList, String contentType) {
- log.info("Starting batch insert for {} {} items", contentList.size(), contentType);
-
- // Process in batches to avoid memory issues and improve performance
- List> batches = partition(contentList, BATCH_SIZE);
-
- int totalInserted = 0;
- for (int i = 0; i < batches.size(); i++) {
- List batch = batches.get(i);
-
- try {
- int inserted = contentLibraryService.batchInsertContent(batch);
- totalInserted += inserted;
-
- log.info("Batch {}/{} completed: {} items inserted", i + 1, batches.size(), inserted);
- stats.addInsertedCount(inserted);
-
- if (inserted != batch.size()) {
- log.warn("Batch insert incomplete: expected {}, inserted {}", batch.size(), inserted);
- }
-
- } catch (Exception e) {
- log.error("Failed to insert batch {}/{}: {}", i + 1, batches.size(), e.getMessage(), e);
- stats.addFailedBatch(i + 1, e.getMessage());
- }
- }
-
- log.info("Batch insert completed for {}: {} total items inserted", contentType, totalInserted);
- }
-
- /**
- * Print migration summary
- */
- private void printMigrationSummary() {
- log.info("================== MIGRATION SUMMARY ==================");
- log.info("Total items processed: {}", stats.getTotalProcessed());
- log.info("Total items inserted: {}", stats.getTotalInserted());
- log.info("Total failed items: {}", stats.getTotalFailed());
- log.info("");
-
- log.info("MUSIC CONTENT:");
- for (String language : stats.getProcessedLanguages().keySet()) {
- log.info(" - {}: {} items", language, stats.getProcessedLanguages().get(language));
- }
-
- log.info("STORY CONTENT:");
- for (String genre : stats.getProcessedGenres().keySet()) {
- log.info(" - {}: {} items", genre, stats.getProcessedGenres().get(genre));
- }
-
- if (!stats.getFailedLanguages().isEmpty()) {
- log.error("FAILED LANGUAGES:");
- stats.getFailedLanguages().forEach((lang, error) ->
- log.error(" - {}: {}", lang, error));
- }
-
- if (!stats.getFailedGenres().isEmpty()) {
- log.error("FAILED GENRES:");
- stats.getFailedGenres().forEach((genre, error) ->
- log.error(" - {}: {}", genre, error));
- }
-
- if (!stats.getFailedItems().isEmpty()) {
- log.error("FAILED ITEMS (showing first 10):");
- stats.getFailedItems().entrySet().stream()
- .limit(10)
- .forEach(entry -> log.error(" - {}: {}", entry.getKey(), entry.getValue()));
- }
-
- if (!stats.getFailedBatches().isEmpty()) {
- log.error("FAILED BATCHES:");
- stats.getFailedBatches().forEach((batch, error) ->
- log.error(" - Batch {}: {}", batch, error));
- }
-
- log.info("======================================================");
- }
-
- // Helper methods
-
- /**
- * Safely get string value from JSON object
- */
- private String getJsonString(JsonObject jsonObject, String key) {
- JsonElement element = jsonObject.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
- }
-
- /**
- * Safely get integer value from JSON object
- */
- private Integer getJsonInteger(JsonObject jsonObject, String key) {
- JsonElement element = jsonObject.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
- }
-
- /**
- * Safely get long value from JSON object
- */
- private Long getJsonLong(JsonObject jsonObject, String key) {
- JsonElement element = jsonObject.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
- }
-
- /**
- * Partition list into smaller batches
- */
- private List> partition(List list, int size) {
- List> partitions = new ArrayList<>();
- for (int i = 0; i < list.size(); i += size) {
- partitions.add(list.subList(i, Math.min(i + size, list.size())));
- }
- return partitions;
- }
-
- /**
- * Migration statistics tracker
- */
- private static class MigrationStatistics {
- private final Map processedLanguages = new HashMap<>();
- private final Map processedGenres = new HashMap<>();
- private final Map failedLanguages = new HashMap<>();
- private final Map failedGenres = new HashMap<>();
- private final Map failedItems = new HashMap<>();
- private final Map failedBatches = new HashMap<>();
- private int totalInserted = 0;
-
- public void addProcessedLanguage(String language, int count) {
- processedLanguages.put(language, count);
- }
-
- public void addProcessedGenre(String genre, int count) {
- processedGenres.put(genre, count);
- }
-
- public void addFailedLanguage(String language, String error) {
- failedLanguages.put(language, error);
- }
-
- public void addFailedGenre(String genre, String error) {
- failedGenres.put(genre, error);
- }
-
- public void addFailedItem(String item, String error) {
- failedItems.put(item, error);
- }
-
- public void addFailedBatch(int batchNumber, String error) {
- failedBatches.put(batchNumber, error);
- }
-
- public void addInsertedCount(int count) {
- totalInserted += count;
- }
-
- public int getTotalProcessed() {
- return processedLanguages.values().stream().mapToInt(Integer::intValue).sum() +
- processedGenres.values().stream().mapToInt(Integer::intValue).sum();
- }
-
- public int getTotalFailed() {
- return failedItems.size();
- }
-
- // Getters
- public Map getProcessedLanguages() { return processedLanguages; }
- public Map getProcessedGenres() { return processedGenres; }
- public Map getFailedLanguages() { return failedLanguages; }
- public Map getFailedGenres() { return failedGenres; }
- public Map getFailedItems() { return failedItems; }
- public Map getFailedBatches() { return failedBatches; }
- public int getTotalInserted() { return totalInserted; }
- }
-}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java
deleted file mode 100644
index ea5ce572c..000000000
--- a/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package xiaozhi.migration;
-
-import lombok.Data;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-
-import jakarta.annotation.PostConstruct;
-import java.io.File;
-import java.util.List;
-
-/**
- * Configuration class for Content Library Migration
- *
- * This class manages all migration-specific configuration properties
- * and provides validation for paths and settings.
- *
- * @author Data Migration Configuration
- * @version 1.0
- */
-@Data
-@Configuration
-@Profile("migration")
-@ConfigurationProperties(prefix = "migration.content-library")
-public class MigrationConfiguration {
-
- /**
- * Base path for xiaozhi-server directory
- */
- private String basePath = System.getProperty("user.dir") + "/xiaozhi-server";
-
- /**
- * Batch size for database operations
- */
- private int batchSize = 100;
-
- /**
- * Whether to skip migration if content already exists
- */
- private boolean skipIfExists = false;
-
- /**
- * Connection timeout in milliseconds
- */
- private int connectionTimeout = 30000;
-
- /**
- * Read timeout in milliseconds
- */
- private int readTimeout = 60000;
-
- /**
- * Music directory path
- */
- private String musicPath;
-
- /**
- * Stories directory path
- */
- private String storiesPath;
-
- /**
- * Music configuration
- */
- private MusicConfig music = new MusicConfig();
-
- /**
- * Stories configuration
- */
- private StoriesConfig stories = new StoriesConfig();
-
- @PostConstruct
- public void init() {
- // Override with environment variables if present
- String envBasePath = System.getenv("MIGRATION_BASE_PATH");
- if (envBasePath != null && !envBasePath.trim().isEmpty()) {
- this.basePath = envBasePath;
- }
-
- String envBatchSize = System.getenv("MIGRATION_BATCH_SIZE");
- if (envBatchSize != null && !envBatchSize.trim().isEmpty()) {
- try {
- this.batchSize = Integer.parseInt(envBatchSize);
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Invalid MIGRATION_BATCH_SIZE value: " + envBatchSize);
- }
- }
-
- // Set derived paths if not already set
- if (musicPath == null) {
- musicPath = basePath + "/music";
- }
-
- if (storiesPath == null) {
- storiesPath = basePath + "/stories";
- }
-
- // Validate configuration
- validateConfiguration();
- }
-
- /**
- * Validate migration configuration
- */
- private void validateConfiguration() {
- validatePath(basePath, "Base path");
- validatePath(musicPath, "Music path");
- validatePath(storiesPath, "Stories path");
-
- if (batchSize <= 0 || batchSize > 1000) {
- throw new IllegalArgumentException("Batch size must be between 1 and 1000, got: " + batchSize);
- }
-
- if (connectionTimeout <= 0) {
- throw new IllegalArgumentException("Connection timeout must be positive, got: " + connectionTimeout);
- }
-
- if (readTimeout <= 0) {
- throw new IllegalArgumentException("Read timeout must be positive, got: " + readTimeout);
- }
- }
-
- /**
- * Validate that a path exists
- */
- private void validatePath(String path, String description) {
- if (path == null || path.trim().isEmpty()) {
- throw new IllegalArgumentException(description + " cannot be empty");
- }
-
- File file = new File(path);
- if (!file.exists()) {
- throw new IllegalArgumentException(description + " does not exist: " + path);
- }
-
- if (!file.isDirectory()) {
- throw new IllegalArgumentException(description + " is not a directory: " + path);
- }
- }
-
- /**
- * Get absolute path for music directory
- */
- public String getAbsoluteMusicPath() {
- return new File(musicPath).getAbsolutePath();
- }
-
- /**
- * Get absolute path for stories directory
- */
- public String getAbsoluteStoriesPath() {
- return new File(storiesPath).getAbsolutePath();
- }
-
- /**
- * Get absolute base path
- */
- public String getAbsoluteBasePath() {
- return new File(basePath).getAbsolutePath();
- }
-
- /**
- * Music content configuration
- */
- @Data
- public static class MusicConfig {
- private String contentType = "music";
- private List supportedLanguages = List.of(
- "English", "Hindi", "Kannada", "Phonics", "Telugu"
- );
- }
-
- /**
- * Stories content configuration
- */
- @Data
- public static class StoriesConfig {
- private String contentType = "story";
- private List supportedGenres = List.of(
- "Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"
- );
- }
-
- /**
- * Check if a language is supported for music content
- */
- public boolean isSupportedMusicLanguage(String language) {
- return music.getSupportedLanguages().contains(language);
- }
-
- /**
- * Check if a genre is supported for story content
- */
- public boolean isSupportedStoryGenre(String genre) {
- return stories.getSupportedGenres().contains(genre);
- }
-}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java
deleted file mode 100644
index 260837fb7..000000000
--- a/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package xiaozhi.migration;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.context.annotation.ComponentScan;
-
-/**
- * Standalone Migration Runner
- *
- * This class provides a standalone entry point for running the content library migration
- * without starting the full application.
- *
- * Usage:
- * 1. Command line: mvn exec:java -Dexec.mainClass="xiaozhi.migration.MigrationRunner" -Dspring.profiles.active=migration
- * 2. IDE: Run this class directly with VM options: -Dspring.profiles.active=migration
- * 3. JAR: java -cp app.jar xiaozhi.migration.MigrationRunner --spring.profiles.active=migration
- *
- * Environment Variables:
- * - XIAOZHI_SERVER_PATH: Override the default xiaozhi-server path
- * - MIGRATION_BATCH_SIZE: Override the default batch size (default: 100)
- * - MIGRATION_BASE_PATH: Override the base path for migration files
- *
- * The migration process will:
- * 1. Scan xiaozhi-server/music/[language]/metadata.json files
- * 2. Scan xiaozhi-server/stories/[genre]/metadata.json files
- * 3. Parse JSON content and create ContentLibraryDTO objects
- * 4. Batch insert content into the content_library table
- * 5. Provide detailed logging and statistics
- *
- * @author Data Migration Script Generator
- * @version 1.0
- */
-@Slf4j
-@SpringBootApplication
-@ComponentScan(basePackages = {
- "xiaozhi.migration", // Migration components
- "xiaozhi.modules.content", // Content service components
- "xiaozhi.common", // Common utilities
- "xiaozhi.config" // Configuration classes
-})
-public class MigrationRunner {
-
- public static void main(String[] args) {
- log.info("=======================================================");
- log.info("XiaoZhi Content Library Migration Runner");
- log.info("=======================================================");
-
- // Set migration profile if not already set
- String profiles = System.getProperty("spring.profiles.active");
- if (profiles == null || !profiles.contains("migration")) {
- System.setProperty("spring.profiles.active", "migration");
- log.info("Setting spring profile to 'migration'");
- }
-
- // Log environment configuration
- logEnvironmentInfo();
-
- try {
- // Create Spring context and run migration
- SpringApplication app = new SpringApplication(MigrationRunner.class);
-
- // Disable web environment for migration
- app.setWebApplicationType(org.springframework.boot.WebApplicationType.NONE);
-
- // Disable banner for cleaner output
- app.setBannerMode(org.springframework.boot.Banner.Mode.OFF);
-
- // Run the application
- var context = app.run(args);
-
- log.info("Migration completed successfully!");
- log.info("Application context will be closed automatically");
-
- // Gracefully shutdown
- SpringApplication.exit(context, () -> 0);
-
- } catch (Exception e) {
- log.error("Migration failed with error: {}", e.getMessage(), e);
- System.exit(1);
- }
- }
-
- /**
- * Log environment configuration for debugging
- */
- private static void logEnvironmentInfo() {
- log.info("Environment Configuration:");
- log.info(" - Java Version: {}", System.getProperty("java.version"));
- log.info(" - Working Directory: {}", System.getProperty("user.dir"));
- log.info(" - Spring Profiles: {}", System.getProperty("spring.profiles.active", "default"));
-
- String xiaozhiPath = System.getenv("XIAOZHI_SERVER_PATH");
- if (xiaozhiPath != null) {
- log.info(" - XiaoZhi Server Path (env): {}", xiaozhiPath);
- }
-
- String batchSize = System.getenv("MIGRATION_BATCH_SIZE");
- if (batchSize != null) {
- log.info(" - Batch Size (env): {}", batchSize);
- }
-
- String basePath = System.getenv("MIGRATION_BASE_PATH");
- if (basePath != null) {
- log.info(" - Base Path (env): {}", basePath);
- }
-
- log.info("=======================================================");
- }
-}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java
deleted file mode 100644
index 573bab245..000000000
--- a/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java
+++ /dev/null
@@ -1,284 +0,0 @@
-package xiaozhi.migration;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.CommandLineRunner;
-import org.springframework.stereotype.Component;
-import org.springframework.context.annotation.Profile;
-
-import xiaozhi.modules.content.service.ContentLibraryService;
-import xiaozhi.modules.content.dto.ContentSearchDTO;
-import xiaozhi.common.page.PageData;
-import xiaozhi.modules.content.dto.ContentLibraryDTO;
-
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-
-/**
- * Migration Validator
- *
- * This component validates the migrated content library data to ensure
- * the migration was successful and data integrity is maintained.
- *
- * Run with: java -jar app.jar --spring.profiles.active=validation
- *
- * @author Migration Validator
- * @version 1.0
- */
-@Slf4j
-@Component
-@Profile("validation")
-public class MigrationValidator implements CommandLineRunner {
-
- @Autowired
- private ContentLibraryService contentLibraryService;
-
- @Override
- public void run(String... args) throws Exception {
- log.info("=======================================================");
- log.info("Content Library Migration Validation");
- log.info("=======================================================");
-
- try {
- // Validate content statistics
- validateContentStatistics();
-
- // Validate content categories
- validateCategories();
-
- // Validate sample content
- validateSampleContent();
-
- // Validate search functionality
- validateSearchFunctionality();
-
- log.info("=======================================================");
- log.info("Migration Validation COMPLETED SUCCESSFULLY");
- log.info("=======================================================");
-
- } catch (Exception e) {
- log.error("Migration validation failed: {}", e.getMessage(), e);
- throw e;
- }
- }
-
- /**
- * Validate content statistics
- */
- private void validateContentStatistics() {
- log.info("Validating content statistics...");
-
- Object statsObj = contentLibraryService.getContentStatistics();
- if (!(statsObj instanceof Map)) {
- throw new RuntimeException("Invalid statistics format returned");
- }
-
- @SuppressWarnings("unchecked")
- Map stats = (Map) statsObj;
-
- Integer totalMusic = (Integer) stats.get("totalMusic");
- Integer totalStories = (Integer) stats.get("totalStories");
- Integer totalContent = (Integer) stats.get("totalContent");
-
- log.info("Content Statistics:");
- log.info(" - Total Music: {}", totalMusic != null ? totalMusic : 0);
- log.info(" - Total Stories: {}", totalStories != null ? totalStories : 0);
- log.info(" - Total Content: {}", totalContent != null ? totalContent : 0);
-
- if (totalContent == null || totalContent == 0) {
- throw new RuntimeException("No content found in database - migration may have failed");
- }
-
- if (totalMusic == null) totalMusic = 0;
- if (totalStories == null) totalStories = 0;
-
- if (!totalContent.equals(totalMusic + totalStories)) {
- throw new RuntimeException("Content count mismatch: total=" + totalContent +
- ", music=" + totalMusic + ", stories=" + totalStories);
- }
-
- log.info("✓ Content statistics validation passed");
- }
-
- /**
- * Validate content categories
- */
- private void validateCategories() {
- log.info("Validating content categories...");
-
- // Expected categories based on migration script
- String[] expectedMusicLanguages = {"English", "Hindi", "Kannada", "Phonics", "Telugu"};
- String[] expectedStoryGenres = {"Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"};
-
- // Get music categories
- List musicCategories = contentLibraryService.getCategoriesByType("music");
- log.info("Found music categories: {}", musicCategories);
-
- // Get story categories
- List storyCategories = contentLibraryService.getCategoriesByType("story");
- log.info("Found story categories: {}", storyCategories);
-
- // Validate music categories
- for (String expectedLang : expectedMusicLanguages) {
- if (!musicCategories.contains(expectedLang)) {
- log.warn("Expected music language '{}' not found", expectedLang);
- } else {
- log.info("✓ Music language '{}' found", expectedLang);
- }
- }
-
- // Validate story categories
- for (String expectedGenre : expectedStoryGenres) {
- if (!storyCategories.contains(expectedGenre)) {
- log.warn("Expected story genre '{}' not found", expectedGenre);
- } else {
- log.info("✓ Story genre '{}' found", expectedGenre);
- }
- }
-
- log.info("✓ Categories validation completed");
- }
-
- /**
- * Validate sample content
- */
- private void validateSampleContent() {
- log.info("Validating sample content...");
-
- // Test music content
- ContentSearchDTO musicSearch = new ContentSearchDTO();
- musicSearch.setContentType("music");
- musicSearch.setLimit(5);
-
- PageData musicResults = contentLibraryService.getContentList(musicSearch);
-
- if (musicResults.getList() == null || musicResults.getList().isEmpty()) {
- log.warn("No music content found");
- } else {
- log.info("Sample music content ({} items):", musicResults.getList().size());
- for (ContentLibraryDTO content : musicResults.getList()) {
- log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
- content.getFilename());
- validateContentItem(content, "music");
- }
- }
-
- // Test story content
- ContentSearchDTO storySearch = new ContentSearchDTO();
- storySearch.setContentType("story");
- storySearch.setLimit(5);
-
- PageData storyResults = contentLibraryService.getContentList(storySearch);
-
- if (storyResults.getList() == null || storyResults.getList().isEmpty()) {
- log.warn("No story content found");
- } else {
- log.info("Sample story content ({} items):", storyResults.getList().size());
- for (ContentLibraryDTO content : storyResults.getList()) {
- log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
- content.getFilename());
- validateContentItem(content, "story");
- }
- }
-
- log.info("✓ Sample content validation completed");
- }
-
- /**
- * Validate individual content item
- */
- private void validateContentItem(ContentLibraryDTO content, String expectedType) {
- if (content.getId() == null || content.getId().isEmpty()) {
- throw new RuntimeException("Content item missing ID: " + content.getTitle());
- }
-
- if (content.getTitle() == null || content.getTitle().isEmpty()) {
- throw new RuntimeException("Content item missing title: " + content.getId());
- }
-
- if (!expectedType.equals(content.getContentType())) {
- throw new RuntimeException("Content type mismatch for " + content.getTitle() +
- ": expected " + expectedType + ", got " + content.getContentType());
- }
-
- if (content.getCategory() == null || content.getCategory().isEmpty()) {
- throw new RuntimeException("Content item missing category: " + content.getTitle());
- }
-
- if (content.getAlternatives() == null) {
- log.warn("Content item missing alternatives: {}", content.getTitle());
- }
-
- if (content.getIsActive() == null || !content.getIsActive()) {
- log.warn("Content item not active: {}", content.getTitle());
- }
- }
-
- /**
- * Validate search functionality
- */
- private void validateSearchFunctionality() {
- log.info("Validating search functionality...");
-
- // Test basic search
- ContentSearchDTO searchDTO = new ContentSearchDTO();
- searchDTO.setQuery("baby");
- searchDTO.setLimit(10);
-
- PageData searchResults = contentLibraryService.searchContent(searchDTO);
-
- if (searchResults.getList() == null) {
- log.warn("Search returned null results");
- } else {
- log.info("Search for 'baby' returned {} results", searchResults.getList().size());
-
- if (!searchResults.getList().isEmpty()) {
- for (ContentLibraryDTO result : searchResults.getList()) {
- String title = result.getTitle().toLowerCase();
- List alternatives = result.getAlternatives();
-
- boolean containsBaby = title.contains("baby");
- if (!containsBaby && alternatives != null) {
- containsBaby = alternatives.stream()
- .anyMatch(alt -> alt.toLowerCase().contains("baby"));
- }
-
- if (containsBaby) {
- log.info("✓ Search result matches: {}", result.getTitle());
- } else {
- log.warn("Search result may not match query: {}", result.getTitle());
- }
- }
- }
- }
-
- // Test category filtering
- ContentSearchDTO categorySearch = new ContentSearchDTO();
- categorySearch.setContentType("music");
- categorySearch.setCategory("English");
- categorySearch.setLimit(5);
-
- PageData categoryResults = contentLibraryService.getContentList(categorySearch);
-
- if (categoryResults.getList() == null || categoryResults.getList().isEmpty()) {
- log.warn("No English music content found");
- } else {
- log.info("Found {} English music items", categoryResults.getList().size());
-
- for (ContentLibraryDTO result : categoryResults.getList()) {
- if (!"music".equals(result.getContentType())) {
- throw new RuntimeException("Category search returned wrong content type: " +
- result.getContentType());
- }
- if (!"English".equals(result.getCategory())) {
- throw new RuntimeException("Category search returned wrong category: " +
- result.getCategory());
- }
- }
- log.info("✓ Category filtering works correctly");
- }
-
- log.info("✓ Search functionality validation completed");
- }
-}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java b/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java
deleted file mode 100644
index bcaa7c22f..000000000
--- a/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java
+++ /dev/null
@@ -1,273 +0,0 @@
-package xiaozhi.migration;
-
-import java.io.File;
-import java.nio.file.Files;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.util.*;
-
-import com.google.gson.*;
-
-/**
- * Standalone Content Library Migration
- * Can be run independently to populate the content_library table
- */
-public class StandaloneContentMigration {
-
- // Database configuration - adjust these for your environment
- private static final String DB_URL = "jdbc:mysql://localhost:3306/xiaozhi_esp32?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
- private static final String DB_USER = "root";
- private static final String DB_PASSWORD = "123456";
-
- // Content paths
- private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
- private static final String MUSIC_PATH = BASE_PATH + "/music";
- private static final String STORIES_PATH = BASE_PATH + "/stories";
-
- private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- private static Connection connection;
-
- public static void main(String[] args) {
- System.out.println("==========================================");
- System.out.println("Content Library Standalone Migration");
- System.out.println("==========================================\n");
-
- try {
- // Connect to database
- connectToDatabase();
-
- // Clear existing data (optional - comment out if you want to keep existing data)
- clearExistingData();
-
- // Migrate music
- migrateMusicContent();
-
- // Migrate stories
- migrateStoryContent();
-
- // Print summary
- printSummary();
-
- System.out.println("\nMigration completed successfully!");
-
- } catch (Exception e) {
- System.err.println("Migration failed: " + e.getMessage());
- e.printStackTrace();
- } finally {
- closeConnection();
- }
- }
-
- private static void connectToDatabase() throws Exception {
- System.out.println("Connecting to database...");
- Class.forName("com.mysql.cj.jdbc.Driver");
- connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
- connection.setAutoCommit(false);
- System.out.println("Connected to database successfully\n");
- }
-
- private static void clearExistingData() throws Exception {
- System.out.println("Clearing existing data...");
- PreparedStatement stmt = connection.prepareStatement("DELETE FROM content_library");
- int deleted = stmt.executeUpdate();
- connection.commit();
- System.out.println("Deleted " + deleted + " existing records\n");
- }
-
- private static void migrateMusicContent() throws Exception {
- System.out.println("Migrating music content...");
-
- File musicDir = new File(MUSIC_PATH);
- File[] languageDirs = musicDir.listFiles(File::isDirectory);
-
- if (languageDirs == null) {
- System.out.println("No music directories found");
- return;
- }
-
- int totalMusic = 0;
- for (File langDir : languageDirs) {
- String language = langDir.getName();
- System.out.println(" Processing language: " + language);
-
- File metadataFile = new File(langDir, "metadata.json");
- if (!metadataFile.exists()) {
- System.out.println(" No metadata.json found");
- continue;
- }
-
- String jsonContent = Files.readString(metadataFile.toPath());
- JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
-
- int count = 0;
- for (Map.Entry entry : jsonObject.entrySet()) {
- String title = entry.getKey();
- JsonObject info = entry.getValue().getAsJsonObject();
-
- if (insertContentItem(title, info, "music", language)) {
- count++;
- }
- }
-
- System.out.println(" Inserted " + count + " items");
- totalMusic += count;
- }
-
- connection.commit();
- System.out.println("Total music items migrated: " + totalMusic + "\n");
- }
-
- private static void migrateStoryContent() throws Exception {
- System.out.println("Migrating story content...");
-
- File storiesDir = new File(STORIES_PATH);
- File[] genreDirs = storiesDir.listFiles(File::isDirectory);
-
- if (genreDirs == null) {
- System.out.println("No story directories found");
- return;
- }
-
- int totalStories = 0;
- for (File genreDir : genreDirs) {
- String genre = genreDir.getName();
- System.out.println(" Processing genre: " + genre);
-
- File metadataFile = new File(genreDir, "metadata.json");
- if (!metadataFile.exists()) {
- System.out.println(" No metadata.json found");
- continue;
- }
-
- String jsonContent = Files.readString(metadataFile.toPath());
- JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
-
- int count = 0;
- for (Map.Entry entry : jsonObject.entrySet()) {
- String title = entry.getKey();
- JsonObject info = entry.getValue().getAsJsonObject();
-
- if (insertContentItem(title, info, "story", genre)) {
- count++;
- }
- }
-
- System.out.println(" Inserted " + count + " items");
- totalStories += count;
- }
-
- connection.commit();
- System.out.println("Total story items migrated: " + totalStories + "\n");
- }
-
- private static boolean insertContentItem(String title, JsonObject info, String contentType, String category) {
- try {
- String sql = "INSERT INTO content_library (id, title, romanized, filename, content_type, " +
- "category, alternatives, aws_s3_url, duration_seconds, file_size_bytes, is_active) " +
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
-
- PreparedStatement stmt = connection.prepareStatement(sql);
-
- // Generate UUID
- String id = UUID.randomUUID().toString();
-
- // Get values from JSON
- String romanized = getJsonString(info, "romanized");
- String filename = getJsonString(info, "filename");
-
- // Build alternatives JSON array
- JsonArray alternativesArray = info.getAsJsonArray("alternatives");
- String alternativesJson = null;
- if (alternativesArray != null) {
- alternativesJson = gson.toJson(alternativesArray);
- }
-
- // Set parameters
- stmt.setString(1, id);
- stmt.setString(2, title);
- stmt.setString(3, romanized);
- stmt.setString(4, filename);
- stmt.setString(5, contentType);
- stmt.setString(6, category);
- stmt.setString(7, alternativesJson);
- stmt.setString(8, getJsonString(info, "aws_s3_url")); // May be null
- stmt.setObject(9, getJsonInteger(info, "duration_seconds")); // May be null
- stmt.setObject(10, getJsonLong(info, "file_size_bytes")); // May be null
- stmt.setInt(11, 1); // is_active
-
- stmt.executeUpdate();
- return true;
-
- } catch (Exception e) {
- System.err.println(" Failed to insert '" + title + "': " + e.getMessage());
- return false;
- }
- }
-
- private static String getJsonString(JsonObject obj, String key) {
- JsonElement element = obj.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
- }
-
- private static Integer getJsonInteger(JsonObject obj, String key) {
- JsonElement element = obj.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
- }
-
- private static Long getJsonLong(JsonObject obj, String key) {
- JsonElement element = obj.get(key);
- return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
- }
-
- private static void printSummary() throws Exception {
- System.out.println("==========================================");
- System.out.println("Migration Summary");
- System.out.println("==========================================");
-
- // Count records by type
- PreparedStatement stmt = connection.prepareStatement(
- "SELECT content_type, COUNT(*) as count FROM content_library GROUP BY content_type"
- );
- ResultSet rs = stmt.executeQuery();
-
- while (rs.next()) {
- String type = rs.getString("content_type");
- int count = rs.getInt("count");
- System.out.println(type.toUpperCase() + ": " + count + " items");
- }
-
- // Count by category
- System.out.println("\nBy Category:");
- stmt = connection.prepareStatement(
- "SELECT content_type, category, COUNT(*) as count FROM content_library " +
- "GROUP BY content_type, category ORDER BY content_type, category"
- );
- rs = stmt.executeQuery();
-
- String lastType = "";
- while (rs.next()) {
- String type = rs.getString("content_type");
- String category = rs.getString("category");
- int count = rs.getInt("count");
-
- if (!type.equals(lastType)) {
- System.out.println("\n" + type.toUpperCase() + ":");
- lastType = type;
- }
- System.out.println(" - " + category + ": " + count);
- }
- }
-
- private static void closeConnection() {
- try {
- if (connection != null && !connection.isClosed()) {
- connection.close();
- System.out.println("\nDatabase connection closed");
- }
- } catch (Exception e) {
- System.err.println("Error closing connection: " + e.getMessage());
- }
- }
-}
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml
index 58970199e..9bc3631c6 100644
--- a/main/manager-api/src/main/resources/application-dev.yml
+++ b/main/manager-api/src/main/resources/application-dev.yml
@@ -7,6 +7,10 @@ knife4j:
password: 2ZABCDEUgF
setting:
enableFooter: false
+
+# Server configuration
+server:
+ secret: d153e93c-bb2f-42e7-8045-a1ee47a1dcfc
spring:
datasource:
druid:
@@ -18,9 +22,9 @@ spring:
# password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK
driver-class-name: com.mysql.cj.jdbc.Driver
# Railway MySQL Configuration - Updated for Railway database
- url: jdbc:mysql://nozomi.proxy.rlwy.net:25037/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
+ url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
username: root
- password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm
+ password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA
initial-size: 10
max-active: 100
@@ -46,9 +50,9 @@ spring:
data:
redis:
# Railway Redis Configuration
- host: maglev.proxy.rlwy.net # Railway Redis服务器地址
- port: 16780 # Railway Redis服务器连接端口
- password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP # Railway Redis服务器连接密码
+ host: yamanote.proxy.rlwy.net # Railway Redis服务器地址
+ port: 34938 # Railway Redis服务器连接端口
+ password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码
username: default # Railway Redis用户名
database: 0 # Redis数据库索引(默认为0)
timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间
diff --git a/main/manager-api/src/main/resources/db/changelog/202509020001_add_openai_gemini_tts_fixed.sql b/main/manager-api/src/main/resources/db/changelog/202509020001_add_openai_gemini_tts_fixed.sql
new file mode 100644
index 000000000..4facb8d7d
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509020001_add_openai_gemini_tts_fixed.sql
@@ -0,0 +1,24 @@
+-- Add OpenAI TTS and Gemini TTS providers to dashboard
+-- -------------------------------------------------------
+
+-- Add OpenAI TTS provider (only if it doesn't exist)
+INSERT IGNORE INTO `ai_model_config` VALUES (
+ 'TTS_OpenAITTS',
+ 'TTS',
+ 'OpenAITTS',
+ 'OpenAI TTS语音合成',
+ 0, 1,
+ '{"type": "openai", "api_key": "你的api_key", "api_url": "https://api.openai.com/v1/audio/speech", "model": "tts-1", "voice": "alloy", "speed": 1.0, "format": "wav", "output_dir": "tmp/"}',
+ NULL, NULL, 16, NULL, NULL, NULL, NULL
+);
+
+-- Add Gemini TTS provider (only if it doesn't exist)
+INSERT IGNORE INTO `ai_model_config` VALUES (
+ 'TTS_GeminiTTS',
+ 'TTS',
+ 'GeminiTTS',
+ 'Google Gemini TTS语音合成',
+ 0, 1,
+ '{"type": "gemini", "api_key": "你的api_key", "api_url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent", "model": "gemini-2.5-flash-preview-tts", "voice": "Zephyr", "language": "en", "output_dir": "tmp/"}',
+ NULL, NULL, 17, NULL, NULL, NULL, NULL
+);
diff --git a/main/manager-api/src/main/resources/db/changelog/202509020002_add_openai_gemini_voices_fixed.sql b/main/manager-api/src/main/resources/db/changelog/202509020002_add_openai_gemini_voices_fixed.sql
new file mode 100644
index 000000000..3f31a768b
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509020002_add_openai_gemini_voices_fixed.sql
@@ -0,0 +1,20 @@
+-- Add voice options for OpenAI TTS and Gemini TTS providers
+-- -------------------------------------------------------
+
+-- OpenAI TTS Voices (only if they don't exist)
+INSERT IGNORE INTO `ai_tts_voice` VALUES
+('TTS_OpenAI0001', 'TTS_OpenAITTS', 'Alloy - Neutral', 'alloy', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_OpenAI0002', 'TTS_OpenAITTS', 'Echo - Male', 'echo', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_OpenAI0003', 'TTS_OpenAITTS', 'Fable - British', 'fable', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_OpenAI0004', 'TTS_OpenAITTS', 'Onyx - Deep Male', 'onyx', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_OpenAI0005', 'TTS_OpenAITTS', 'Nova - Female', 'nova', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_OpenAI0006', 'TTS_OpenAITTS', 'Shimmer - Soft Female', 'shimmer', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL);
+
+-- Gemini TTS Voices (only if they don't exist)
+INSERT IGNORE INTO `ai_tts_voice` VALUES
+('TTS_Gemini0001', 'TTS_GeminiTTS', 'Zephyr - Bright', 'Zephyr', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_Gemini0002', 'TTS_GeminiTTS', 'Puck - Upbeat', 'Puck', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_Gemini0003', 'TTS_GeminiTTS', 'Charon - Deep', 'Charon', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_Gemini0004', 'TTS_GeminiTTS', 'Kore - Warm', 'Kore', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_Gemini0005', 'TTS_GeminiTTS', 'Fenrir - Strong', 'Fenrir', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL),
+('TTS_Gemini0006', 'TTS_GeminiTTS', 'Aoede - Musical', 'Aoede', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL);
diff --git a/main/manager-api/src/main/resources/db/changelog/202509020003_add_openai_gemini_tts_providers.sql b/main/manager-api/src/main/resources/db/changelog/202509020003_add_openai_gemini_tts_providers.sql
new file mode 100644
index 000000000..9418b6a97
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509020003_add_openai_gemini_tts_providers.sql
@@ -0,0 +1,13 @@
+-- Add OpenAI TTS and Gemini TTS providers to ai_model_provider table
+-- This file adds the provider definitions needed for the dashboard dropdown
+-- -----------------------------------------------------------------------
+
+-- Add OpenAI TTS provider definition
+DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_TTS_OpenAITTS';
+INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
+('SYSTEM_TTS_OpenAITTS', 'TTS', 'openai', 'OpenAI TTS语音合成', '[{"key":"api_key","label":"API密钥","type":"string","required":true},{"key":"api_url","label":"API地址","type":"string","required":true},{"key":"model","label":"模型","type":"string","required":true},{"key":"voice","label":"音色","type":"string","required":true},{"key":"speed","label":"语速","type":"number"},{"key":"output_dir","label":"输出目录","type":"string"}]', 18, 1, NOW(), 1, NOW());
+
+-- Add Gemini TTS provider definition
+DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_TTS_GeminiTTS';
+INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
+('SYSTEM_TTS_GeminiTTS', 'TTS', 'gemini', 'Google Gemini TTS语音合成', '[{"key":"api_key","label":"API密钥","type":"string","required":true},{"key":"api_url","label":"API地址","type":"string","required":true},{"key":"model","label":"模型","type":"string","required":true},{"key":"voice","label":"音色","type":"string","required":true},{"key":"language","label":"语言","type":"string"},{"key":"output_dir","label":"输出目录","type":"string"}]', 19, 1, NOW(), 1, NOW());
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509020004_clear_liquibase_checksums.sql b/main/manager-api/src/main/resources/db/changelog/202509020004_clear_liquibase_checksums.sql
new file mode 100644
index 000000000..15194536c
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509020004_clear_liquibase_checksums.sql
@@ -0,0 +1,12 @@
+-- Clear Liquibase checksums for modified changesets
+-- This allows the updated TTS configurations to be applied
+-- -------------------------------------------------------
+
+-- Update the checksum for the modified changeset
+UPDATE DATABASECHANGELOG
+SET MD5SUM = NULL
+WHERE ID = '202509020001' AND AUTHOR = 'claude';
+
+-- Clear any locks
+DELETE FROM DATABASECHANGELOGLOCK WHERE ID = 1;
+INSERT INTO DATABASECHANGELOGLOCK (ID, LOCKED, LOCKGRANTED, LOCKEDBY) VALUES (1, 0, NULL, NULL);
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509020005_update_tts_configs.sql b/main/manager-api/src/main/resources/db/changelog/202509020005_update_tts_configs.sql
new file mode 100644
index 000000000..07f5d0286
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509020005_update_tts_configs.sql
@@ -0,0 +1,15 @@
+-- Update existing TTS configurations with proper API keys and model codes
+-- This replaces the modified 202509020001 changeset to avoid checksum issues
+-- -----------------------------------------------------------------------
+
+-- Update OpenAI TTS configuration with proper API key and model code
+UPDATE `ai_model_config` SET
+ `model_code` = 'openai',
+ `config_json` = '{"type": "openai", "api_key": "YOUR_OPENAI_API_KEY", "api_url": "https://api.openai.com/v1/audio/speech", "model": "tts-1", "voice": "alloy", "speed": 1.0, "output_dir": "tmp/"}'
+WHERE `id` = 'TTS_OpenAITTS';
+
+-- Update Gemini TTS configuration with proper API key and model code
+UPDATE `ai_model_config` SET
+ `model_code` = 'gemini',
+ `config_json` = '{"type": "gemini", "api_key": "YOUR_GEMINI_API_KEY", "api_url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent", "model": "gemini-2.5-flash-preview-tts", "voice": "Zephyr", "language": "en", "output_dir": "tmp/"}'
+WHERE `id` = 'TTS_GeminiTTS';
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509030001_clear_tts_config_checksum.sql b/main/manager-api/src/main/resources/db/changelog/202509030001_clear_tts_config_checksum.sql
new file mode 100644
index 000000000..5b3338694
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509030001_clear_tts_config_checksum.sql
@@ -0,0 +1,8 @@
+-- Clear checksum for the modified TTS configuration changeset
+-- This allows the updated changeset with placeholder API keys to be applied
+-- -------------------------------------------------------------------------
+
+-- Clear the checksum for the modified changeset 202509020005
+UPDATE DATABASECHANGELOG
+SET MD5SUM = NULL
+WHERE ID = '202509020005' AND AUTHOR = 'claude';
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index 49ff76f5e..5c5373c9d 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -367,4 +367,47 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202508291600_add_play_story.sql
+ - changeSet:
+ id: 202509020001
+ author: claude
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509020001_add_openai_gemini_tts_fixed.sql
+ - changeSet:
+ id: 202509020002
+ author: claude
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509020002_add_openai_gemini_voices_fixed.sql
+ - changeSet:
+ id: 202509020003
+ author: claude
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509020003_add_openai_gemini_tts_providers.sql
+ - changeSet:
+ id: 202509020004
+ author: claude
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509020004_clear_liquibase_checksums.sql
+ - changeSet:
+ id: 202509020005
+ author: claude
+ validCheckSum: 8:84e92fe6edb605f91c8c0c0802ba0e27
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509020005_update_tts_configs.sql
+ - changeSet:
+ id: 202509030001
+ author: claude
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509030001_clear_tts_config_checksum.sql
diff --git a/main/mqtt-gateway/config/mqtt.json b/main/mqtt-gateway/config/mqtt.json
index 8200b3e23..c8c058877 100644
--- a/main/mqtt-gateway/config/mqtt.json
+++ b/main/mqtt-gateway/config/mqtt.json
@@ -1,12 +1,12 @@
{
"production": {
"chat_servers": [
- "ws://192.168.1.111:8000/toy/v1/"
+ "ws://192.168.1.179:8000/toy/v1/"
]
},
"development": {
"chat_servers": [
- "ws://192.168.1.111:8000/toy/v1/"
+ "ws://192.168.1.179:8000/toy/v1/"
],
"mac_addresss": [
]
diff --git a/main/xiaozhi-server/asr_logs/asr_log_20250819.csv b/main/xiaozhi-server/asr_logs/asr_log_20250819.csv
deleted file mode 100644
index ea9f1f8b8..000000000
--- a/main/xiaozhi-server/asr_logs/asr_log_20250819.csv
+++ /dev/null
@@ -1,18 +0,0 @@
-timestamp,filename,file_path,audio_length_seconds,transcript
-2025-08-19T16:08:05.493297,asr_base_2dd24741-ac6c-4828-a180-f7999414a917_e9fd5c4c-825e-4d67-9eb9-75d91eee5267.wav,./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_e9fd5c4c-825e-4d67-9eb9-75d91eee5267.wav,1.3,Hello?
-2025-08-19T16:08:32.506549,asr_base_2dd24741-ac6c-4828-a180-f7999414a917_f393501b-c3bc-4975-b437-180013399835.wav,./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_f393501b-c3bc-4975-b437-180013399835.wav,1.44,And what do you need?
-2025-08-19T16:09:03.361868,asr_base_2dd24741-ac6c-4828-a180-f7999414a917_51f643bf-75db-49ea-86cf-12cc6af1dd39.wav,./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_51f643bf-75db-49ea-86cf-12cc6af1dd39.wav,1.34,Please.
-2025-08-19T16:09:50.764346,asr_base_2dd24741-ac6c-4828-a180-f7999414a917_a5959fd2-b383-4978-b770-d0e71563cf4a.wav,./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_a5959fd2-b383-4978-b770-d0e71563cf4a.wav,3.72,"That is. Next, normally,"
-2025-08-19T16:10:42.086521,asr_base_2dd24741-ac6c-4828-a180-f7999414a917_335316a7-0d9f-4b04-99a6-b11d34259bc9.wav,./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_335316a7-0d9f-4b04-99a6-b11d34259bc9.wav,3.54,It is either not thick.
-2025-08-19T16:12:53.206688,asr_base_48426c85-efe4-4f3b-aaa0-c2ec9e459858_7f2f5ae4-0b63-4414-927e-c22d500fd2a3.wav,./audio_files\asr_base_48426c85-efe4-4f3b-aaa0-c2ec9e459858_7f2f5ae4-0b63-4414-927e-c22d500fd2a3.wav,1.5,Hi.
-2025-08-19T16:19:08.951171,asr_base_1f1f2a82-ae7a-4b5e-a6e2-777f9c9865dd_61f83a27-b8bc-4a41-a454-5b850b940499.wav,./audio_files\asr_base_1f1f2a82-ae7a-4b5e-a6e2-777f9c9865dd_61f83a27-b8bc-4a41-a454-5b850b940499.wav,2.16,Hello? You audible?
-2025-08-19T16:30:05.123260,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_5594908f-10b7-4d9f-b8fd-8ad06d7260eb.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_5594908f-10b7-4d9f-b8fd-8ad06d7260eb.wav,1.78,Hello?
-2025-08-19T16:30:44.698403,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_e127af3c-5a91-4d43-969a-b7001b65e894.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_e127af3c-5a91-4d43-969a-b7001b65e894.wav,2.64,Can you tell me a story?
-2025-08-19T16:31:11.890809,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_7b4f5d27-3844-444a-b25a-c68e55fd9f18.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_7b4f5d27-3844-444a-b25a-c68e55fd9f18.wav,3.08,Can you tell me another story?
-2025-08-19T16:31:38.696327,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_f0579c38-82db-4763-b250-0bd6e565889b.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_f0579c38-82db-4763-b250-0bd6e565889b.wav,3.5,Can you check latest weather condition?
-2025-08-19T16:32:01.685691,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_d9196c95-f1c2-4441-9d05-119d729b5126.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_d9196c95-f1c2-4441-9d05-119d729b5126.wav,3.2,Check latest international news.
-2025-08-19T16:32:39.019435,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0d9cda5e-236a-4763-969e-a2f3558532c5.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0d9cda5e-236a-4763-969e-a2f3558532c5.wav,3.0,Check latest Indian news.
-2025-08-19T16:32:59.588526,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_66aada81-95c9-4346-afc0-924b03d87a40.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_66aada81-95c9-4346-afc0-924b03d87a40.wav,4.58,"I am I'm feeling like this Indian new day. One of us, every day, it's the same."
-2025-08-19T16:33:13.531243,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_bedca933-3045-47b1-8123-00c85d027eb5.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_bedca933-3045-47b1-8123-00c85d027eb5.wav,4.34,Okay.
-2025-08-19T16:33:17.278808,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0a84b574-8102-4e60-872a-c2731708b2c3.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0a84b574-8102-4e60-872a-c2731708b2c3.wav,3.58,Do not say it loud.
-2025-08-19T16:33:28.682311,asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_8a07647b-88dc-4f03-b800-0b9eaecf0f31.wav,./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_8a07647b-88dc-4f03-b800-0b9eaecf0f31.wav,3.66,But this timing issue is a main issue. So
diff --git a/main/xiaozhi-server/asr_logs/asr_log_20250819.txt b/main/xiaozhi-server/asr_logs/asr_log_20250819.txt
deleted file mode 100644
index 9ec3fd18e..000000000
--- a/main/xiaozhi-server/asr_logs/asr_log_20250819.txt
+++ /dev/null
@@ -1,136 +0,0 @@
-
-================================================================================
-Timestamp: 2025-08-19T16:08:05.494599
-Filename: asr_base_2dd24741-ac6c-4828-a180-f7999414a917_e9fd5c4c-825e-4d67-9eb9-75d91eee5267.wav
-Full Path: ./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_e9fd5c4c-825e-4d67-9eb9-75d91eee5267.wav
-Audio Length: 1.30 seconds
-Transcript: Hello?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:08:32.516543
-Filename: asr_base_2dd24741-ac6c-4828-a180-f7999414a917_f393501b-c3bc-4975-b437-180013399835.wav
-Full Path: ./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_f393501b-c3bc-4975-b437-180013399835.wav
-Audio Length: 1.44 seconds
-Transcript: And what do you need?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:09:03.372170
-Filename: asr_base_2dd24741-ac6c-4828-a180-f7999414a917_51f643bf-75db-49ea-86cf-12cc6af1dd39.wav
-Full Path: ./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_51f643bf-75db-49ea-86cf-12cc6af1dd39.wav
-Audio Length: 1.34 seconds
-Transcript: Please.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:09:50.780327
-Filename: asr_base_2dd24741-ac6c-4828-a180-f7999414a917_a5959fd2-b383-4978-b770-d0e71563cf4a.wav
-Full Path: ./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_a5959fd2-b383-4978-b770-d0e71563cf4a.wav
-Audio Length: 3.72 seconds
-Transcript: That is. Next, normally,
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:10:42.101524
-Filename: asr_base_2dd24741-ac6c-4828-a180-f7999414a917_335316a7-0d9f-4b04-99a6-b11d34259bc9.wav
-Full Path: ./audio_files\asr_base_2dd24741-ac6c-4828-a180-f7999414a917_335316a7-0d9f-4b04-99a6-b11d34259bc9.wav
-Audio Length: 3.54 seconds
-Transcript: It is either not thick.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:12:53.218883
-Filename: asr_base_48426c85-efe4-4f3b-aaa0-c2ec9e459858_7f2f5ae4-0b63-4414-927e-c22d500fd2a3.wav
-Full Path: ./audio_files\asr_base_48426c85-efe4-4f3b-aaa0-c2ec9e459858_7f2f5ae4-0b63-4414-927e-c22d500fd2a3.wav
-Audio Length: 1.50 seconds
-Transcript: Hi.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:19:08.963314
-Filename: asr_base_1f1f2a82-ae7a-4b5e-a6e2-777f9c9865dd_61f83a27-b8bc-4a41-a454-5b850b940499.wav
-Full Path: ./audio_files\asr_base_1f1f2a82-ae7a-4b5e-a6e2-777f9c9865dd_61f83a27-b8bc-4a41-a454-5b850b940499.wav
-Audio Length: 2.16 seconds
-Transcript: Hello? You audible?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:30:05.134584
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_5594908f-10b7-4d9f-b8fd-8ad06d7260eb.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_5594908f-10b7-4d9f-b8fd-8ad06d7260eb.wav
-Audio Length: 1.78 seconds
-Transcript: Hello?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:30:44.713442
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_e127af3c-5a91-4d43-969a-b7001b65e894.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_e127af3c-5a91-4d43-969a-b7001b65e894.wav
-Audio Length: 2.64 seconds
-Transcript: Can you tell me a story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:31:11.902818
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_7b4f5d27-3844-444a-b25a-c68e55fd9f18.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_7b4f5d27-3844-444a-b25a-c68e55fd9f18.wav
-Audio Length: 3.08 seconds
-Transcript: Can you tell me another story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:31:38.711325
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_f0579c38-82db-4763-b250-0bd6e565889b.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_f0579c38-82db-4763-b250-0bd6e565889b.wav
-Audio Length: 3.50 seconds
-Transcript: Can you check latest weather condition?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:32:01.700745
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_d9196c95-f1c2-4441-9d05-119d729b5126.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_d9196c95-f1c2-4441-9d05-119d729b5126.wav
-Audio Length: 3.20 seconds
-Transcript: Check latest international news.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:32:39.036818
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0d9cda5e-236a-4763-969e-a2f3558532c5.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0d9cda5e-236a-4763-969e-a2f3558532c5.wav
-Audio Length: 3.00 seconds
-Transcript: Check latest Indian news.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:32:59.603052
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_66aada81-95c9-4346-afc0-924b03d87a40.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_66aada81-95c9-4346-afc0-924b03d87a40.wav
-Audio Length: 4.58 seconds
-Transcript: I am I'm feeling like this Indian new day. One of us, every day, it's the same.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:33:13.547243
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_bedca933-3045-47b1-8123-00c85d027eb5.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_bedca933-3045-47b1-8123-00c85d027eb5.wav
-Audio Length: 4.34 seconds
-Transcript: Okay.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:33:17.298542
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0a84b574-8102-4e60-872a-c2731708b2c3.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_0a84b574-8102-4e60-872a-c2731708b2c3.wav
-Audio Length: 3.58 seconds
-Transcript: Do not say it loud.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-19T16:33:28.697310
-Filename: asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_8a07647b-88dc-4f03-b800-0b9eaecf0f31.wav
-Full Path: ./audio_files\asr_base_b1419915-959d-43c1-90d8-bac7f75613ae_8a07647b-88dc-4f03-b800-0b9eaecf0f31.wav
-Audio Length: 3.66 seconds
-Transcript: But this timing issue is a main issue. So
-================================================================================
diff --git a/main/xiaozhi-server/asr_logs/asr_log_20250821.csv b/main/xiaozhi-server/asr_logs/asr_log_20250821.csv
deleted file mode 100644
index 69048223f..000000000
--- a/main/xiaozhi-server/asr_logs/asr_log_20250821.csv
+++ /dev/null
@@ -1,36 +0,0 @@
-timestamp,filename,file_path,audio_length_seconds,transcript
-2025-08-21T11:29:11.427829,asr_base_2606038f-035a-4652-aa60-9496450919d5_4a2cbdd2-28e3-4521-9cb9-dab2a0137edc.wav,./audio_files\asr_base_2606038f-035a-4652-aa60-9496450919d5_4a2cbdd2-28e3-4521-9cb9-dab2a0137edc.wav,4.66,Hello? Am I audible? Can you listen to me?
-2025-08-21T11:29:20.348497,asr_base_2606038f-035a-4652-aa60-9496450919d5_f0e77821-4c84-4195-89ba-829a56764251.wav,./audio_files\asr_base_2606038f-035a-4652-aa60-9496450919d5_f0e77821-4c84-4195-89ba-829a56764251.wav,2.56,Hello? Can you hear me?
-2025-08-21T11:52:25.561840,asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_9326e7b7-bf0b-4d02-82ed-fd21f1e6f239.wav,./audio_files\asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_9326e7b7-bf0b-4d02-82ed-fd21f1e6f239.wav,2.8,Can you tell me a story?
-2025-08-21T11:52:35.458477,asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_5591ae6b-8013-407d-9180-a5d580e7d522.wav,./audio_files\asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_5591ae6b-8013-407d-9180-a5d580e7d522.wav,2.22,You hear me right now?
-2025-08-21T11:59:25.334870,asr_base_100cdb6f-34b5-407f-bdc4-8249edd0648a_6c55c3b6-e742-4acd-9cf5-1ce132d0c649.wav,./audio_files\asr_base_100cdb6f-34b5-407f-bdc4-8249edd0648a_6c55c3b6-e742-4acd-9cf5-1ce132d0c649.wav,3.0,How may you audible? Can you listen?
-2025-08-21T12:03:30.369315,asr_base_6e250c0e-cc3a-42ab-9e9f-f1f22f2e4fee_b514e2f2-d4af-45a2-b2a7-cec7eae2c4ac.wav,./audio_files\asr_base_6e250c0e-cc3a-42ab-9e9f-f1f22f2e4fee_b514e2f2-d4af-45a2-b2a7-cec7eae2c4ac.wav,5.0,"My people, can you listen to me properly?"
-2025-08-21T12:06:12.565864,asr_base_f923615f-2afa-4214-8459-baa76684f80c_8132f85d-e135-455b-ac8a-910bed6825c0.wav,./audio_files\asr_base_f923615f-2afa-4214-8459-baa76684f80c_8132f85d-e135-455b-ac8a-910bed6825c0.wav,5.76,Hello? How may you audible? Can you listen to me properly?
-2025-08-21T12:06:20.392241,asr_base_f923615f-2afa-4214-8459-baa76684f80c_7535759a-ee67-42c9-993e-ac2c9511091f.wav,./audio_files\asr_base_f923615f-2afa-4214-8459-baa76684f80c_7535759a-ee67-42c9-993e-ac2c9511091f.wav,1.34,"Oh, yes."
-2025-08-21T12:09:07.590133,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_a84e2ecd-d720-467f-9060-10463ca651e2.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_a84e2ecd-d720-467f-9060-10463ca651e2.wav,6.26,Hello? Am I audible? Can you listen to me properly or not? Just checking.
-2025-08-21T12:09:26.595633,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_22d5689c-5c49-4409-84ed-a62891972dc7.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_22d5689c-5c49-4409-84ed-a62891972dc7.wav,2.82,Who is the prime minister of India?
-2025-08-21T12:09:45.371710,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9ffe9484-8bfc-41ba-9a9c-993db1aa3e7c.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9ffe9484-8bfc-41ba-9a9c-993db1aa3e7c.wav,1.72,Sorry.
-2025-08-21T12:10:18.123301,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_c1fd1e7b-d5d6-4707-8d20-fa9090f4a44c.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_c1fd1e7b-d5d6-4707-8d20-fa9090f4a44c.wav,2.36,Can you tell me a story?
-2025-08-21T12:10:45.379524,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_29efcebb-e89c-431f-b159-950686e35867.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_29efcebb-e89c-431f-b159-950686e35867.wav,2.02,You tell me another one?
-2025-08-21T12:11:17.238330,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_f03073a0-8d62-424f-ab31-c06623ab03ef.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_f03073a0-8d62-424f-ab31-c06623ab03ef.wav,1.96,Still speaking.
-2025-08-21T12:11:40.188176,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_ace2be40-e9fd-4e53-a1c0-5c3b6145ffe1.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_ace2be40-e9fd-4e53-a1c0-5c3b6145ffe1.wav,2.56,Am I audible to you?
-2025-08-21T12:12:18.237167,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_031cd0bb-825a-4863-b4b5-ccdce7487c19.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_031cd0bb-825a-4863-b4b5-ccdce7487c19.wav,1.6,Hello
-2025-08-21T12:13:07.340337,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_953adc38-abe4-46db-8da5-10038a981eef.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_953adc38-abe4-46db-8da5-10038a981eef.wav,3.68,Can you check the news?
-2025-08-21T12:13:42.207120,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_b3298b44-ba5b-4f4d-a1d7-d154748ec409.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_b3298b44-ba5b-4f4d-a1d7-d154748ec409.wav,5.28,"Oh, god. Yesterday, I couldn't generate, like, direct looking."
-2025-08-21T12:13:51.748648,asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9fa1dc1b-78fe-4b40-b768-d95d3fe81ddc.wav,./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9fa1dc1b-78fe-4b40-b768-d95d3fe81ddc.wav,4.98,Kind of if you are not No. You have to actually put it on this.
-2025-08-21T12:14:53.645737,asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_e788beda-21c7-481a-9e90-38ac97625815.wav,./audio_files\asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_e788beda-21c7-481a-9e90-38ac97625815.wav,1.94,Tell me a story.
-2025-08-21T12:15:09.201241,asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_8afec574-c896-4df4-b598-f884f114b62f.wav,./audio_files\asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_8afec574-c896-4df4-b598-f884f114b62f.wav,2.76,Tell me another one.
-2025-08-21T12:53:06.325326,asr_base_0b3c7f51-e480-4c3b-b84d-d2d4277eb4b3_b509dc72-fe00-43e1-9c9a-c931fbd963ef.wav,./audio_files\asr_base_0b3c7f51-e480-4c3b-b84d-d2d4277eb4b3_b509dc72-fe00-43e1-9c9a-c931fbd963ef.wav,2.76,Am I audible?
-2025-08-21T12:56:41.953128,asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_b842c092-57d8-458b-b164-f5ea18e4b316.wav,./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_b842c092-57d8-458b-b164-f5ea18e4b316.wav,1.98,Am I audible?
-2025-08-21T12:58:17.146613,asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_408be9af-083f-429e-a676-72ddfaffcf09.wav,./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_408be9af-083f-429e-a676-72ddfaffcf09.wav,5.2,I'm ready. Can you listen to me right now? Can you stay?
-2025-08-21T12:58:36.489836,asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_cb30e24f-2082-42e3-b03f-6a237530ba28.wav,./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_cb30e24f-2082-42e3-b03f-6a237530ba28.wav,3.36,Can you tell me a story?
-2025-08-21T12:59:52.276531,asr_base_65833e66-8628-436b-a1ab-5ef493febef1_c1b8553d-3e73-47ba-81bb-11679a5be488.wav,./audio_files\asr_base_65833e66-8628-436b-a1ab-5ef493febef1_c1b8553d-3e73-47ba-81bb-11679a5be488.wav,1.7,Hello?
-2025-08-21T13:00:33.791937,asr_base_65833e66-8628-436b-a1ab-5ef493febef1_b5015d16-c659-4984-82f8-101e49d031ce.wav,./audio_files\asr_base_65833e66-8628-436b-a1ab-5ef493febef1_b5015d16-c659-4984-82f8-101e49d031ce.wav,4.68,Six piece tenders.
-2025-08-21T13:04:29.321839,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_b46ec7a7-ff6b-48e6-bbb3-274db4db1300.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_b46ec7a7-ff6b-48e6-bbb3-274db4db1300.wav,1.66,Hello?
-2025-08-21T13:04:56.834491,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_324df0a4-836e-41de-9ac4-fbfc24ec5197.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_324df0a4-836e-41de-9ac4-fbfc24ec5197.wav,3.08,Can you tell me a story?
-2025-08-21T13:05:28.802417,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_35baa6c2-5acf-439c-84e5-a0b887f6fc79.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_35baa6c2-5acf-439c-84e5-a0b887f6fc79.wav,2.4,Am I audible to you?
-2025-08-21T13:05:55.586063,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_423b075b-41c0-4707-97bd-496226f53232.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_423b075b-41c0-4707-97bd-496226f53232.wav,2.82,Can you tell me another story?
-2025-08-21T13:06:26.809659,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_8973e288-43cf-4d09-8391-7dc7a38cf925.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_8973e288-43cf-4d09-8391-7dc7a38cf925.wav,2.44,Can I take ten minutes
-2025-08-21T13:06:52.263835,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_a4f22978-8e8a-4dab-9445-823cb70aaff1.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_a4f22978-8e8a-4dab-9445-823cb70aaff1.wav,2.52,Check the method right now.
-2025-08-21T13:07:18.539505,asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_5804d339-f4df-4446-afaa-17cde0720cb8.wav,./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_5804d339-f4df-4446-afaa-17cde0720cb8.wav,2.42,Yeah. That's it.
-2025-08-21T18:24:29.840221,asr_base_72063402-293b-4944-bdf2-6e41b632f775_86a46d2c-5282-4b0e-a95b-6d503e948565.wav,./audio_files\asr_base_72063402-293b-4944-bdf2-6e41b632f775_86a46d2c-5282-4b0e-a95b-6d503e948565.wav,3.96,"Very important. And every day, it's still not clear."
diff --git a/main/xiaozhi-server/asr_logs/asr_log_20250821.txt b/main/xiaozhi-server/asr_logs/asr_log_20250821.txt
deleted file mode 100644
index 9bf72d7bb..000000000
--- a/main/xiaozhi-server/asr_logs/asr_log_20250821.txt
+++ /dev/null
@@ -1,280 +0,0 @@
-
-================================================================================
-Timestamp: 2025-08-21T11:29:11.432325
-Filename: asr_base_2606038f-035a-4652-aa60-9496450919d5_4a2cbdd2-28e3-4521-9cb9-dab2a0137edc.wav
-Full Path: ./audio_files\asr_base_2606038f-035a-4652-aa60-9496450919d5_4a2cbdd2-28e3-4521-9cb9-dab2a0137edc.wav
-Audio Length: 4.66 seconds
-Transcript: Hello? Am I audible? Can you listen to me?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T11:29:20.358947
-Filename: asr_base_2606038f-035a-4652-aa60-9496450919d5_f0e77821-4c84-4195-89ba-829a56764251.wav
-Full Path: ./audio_files\asr_base_2606038f-035a-4652-aa60-9496450919d5_f0e77821-4c84-4195-89ba-829a56764251.wav
-Audio Length: 2.56 seconds
-Transcript: Hello? Can you hear me?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T11:52:25.571514
-Filename: asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_9326e7b7-bf0b-4d02-82ed-fd21f1e6f239.wav
-Full Path: ./audio_files\asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_9326e7b7-bf0b-4d02-82ed-fd21f1e6f239.wav
-Audio Length: 2.80 seconds
-Transcript: Can you tell me a story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T11:52:35.470153
-Filename: asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_5591ae6b-8013-407d-9180-a5d580e7d522.wav
-Full Path: ./audio_files\asr_base_b88c5b4f-bc97-4a7f-89d7-acdc543ff09c_5591ae6b-8013-407d-9180-a5d580e7d522.wav
-Audio Length: 2.22 seconds
-Transcript: You hear me right now?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T11:59:25.346459
-Filename: asr_base_100cdb6f-34b5-407f-bdc4-8249edd0648a_6c55c3b6-e742-4acd-9cf5-1ce132d0c649.wav
-Full Path: ./audio_files\asr_base_100cdb6f-34b5-407f-bdc4-8249edd0648a_6c55c3b6-e742-4acd-9cf5-1ce132d0c649.wav
-Audio Length: 3.00 seconds
-Transcript: How may you audible? Can you listen?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:03:30.383063
-Filename: asr_base_6e250c0e-cc3a-42ab-9e9f-f1f22f2e4fee_b514e2f2-d4af-45a2-b2a7-cec7eae2c4ac.wav
-Full Path: ./audio_files\asr_base_6e250c0e-cc3a-42ab-9e9f-f1f22f2e4fee_b514e2f2-d4af-45a2-b2a7-cec7eae2c4ac.wav
-Audio Length: 5.00 seconds
-Transcript: My people, can you listen to me properly?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:06:12.577515
-Filename: asr_base_f923615f-2afa-4214-8459-baa76684f80c_8132f85d-e135-455b-ac8a-910bed6825c0.wav
-Full Path: ./audio_files\asr_base_f923615f-2afa-4214-8459-baa76684f80c_8132f85d-e135-455b-ac8a-910bed6825c0.wav
-Audio Length: 5.76 seconds
-Transcript: Hello? How may you audible? Can you listen to me properly?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:06:20.405920
-Filename: asr_base_f923615f-2afa-4214-8459-baa76684f80c_7535759a-ee67-42c9-993e-ac2c9511091f.wav
-Full Path: ./audio_files\asr_base_f923615f-2afa-4214-8459-baa76684f80c_7535759a-ee67-42c9-993e-ac2c9511091f.wav
-Audio Length: 1.34 seconds
-Transcript: Oh, yes.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:09:07.601237
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_a84e2ecd-d720-467f-9060-10463ca651e2.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_a84e2ecd-d720-467f-9060-10463ca651e2.wav
-Audio Length: 6.26 seconds
-Transcript: Hello? Am I audible? Can you listen to me properly or not? Just checking.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:09:26.608703
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_22d5689c-5c49-4409-84ed-a62891972dc7.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_22d5689c-5c49-4409-84ed-a62891972dc7.wav
-Audio Length: 2.82 seconds
-Transcript: Who is the prime minister of India?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:09:45.384698
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9ffe9484-8bfc-41ba-9a9c-993db1aa3e7c.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9ffe9484-8bfc-41ba-9a9c-993db1aa3e7c.wav
-Audio Length: 1.72 seconds
-Transcript: Sorry.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:10:18.135193
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_c1fd1e7b-d5d6-4707-8d20-fa9090f4a44c.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_c1fd1e7b-d5d6-4707-8d20-fa9090f4a44c.wav
-Audio Length: 2.36 seconds
-Transcript: Can you tell me a story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:10:45.392855
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_29efcebb-e89c-431f-b159-950686e35867.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_29efcebb-e89c-431f-b159-950686e35867.wav
-Audio Length: 2.02 seconds
-Transcript: You tell me another one?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:11:17.247228
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_f03073a0-8d62-424f-ab31-c06623ab03ef.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_f03073a0-8d62-424f-ab31-c06623ab03ef.wav
-Audio Length: 1.96 seconds
-Transcript: Still speaking.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:11:40.204281
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_ace2be40-e9fd-4e53-a1c0-5c3b6145ffe1.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_ace2be40-e9fd-4e53-a1c0-5c3b6145ffe1.wav
-Audio Length: 2.56 seconds
-Transcript: Am I audible to you?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:12:18.250163
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_031cd0bb-825a-4863-b4b5-ccdce7487c19.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_031cd0bb-825a-4863-b4b5-ccdce7487c19.wav
-Audio Length: 1.60 seconds
-Transcript: Hello
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:13:07.353331
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_953adc38-abe4-46db-8da5-10038a981eef.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_953adc38-abe4-46db-8da5-10038a981eef.wav
-Audio Length: 3.68 seconds
-Transcript: Can you check the news?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:13:42.224709
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_b3298b44-ba5b-4f4d-a1d7-d154748ec409.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_b3298b44-ba5b-4f4d-a1d7-d154748ec409.wav
-Audio Length: 5.28 seconds
-Transcript: Oh, god. Yesterday, I couldn't generate, like, direct looking.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:13:51.761650
-Filename: asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9fa1dc1b-78fe-4b40-b768-d95d3fe81ddc.wav
-Full Path: ./audio_files\asr_base_d56437c8-7f39-4065-8578-8f078f6956cb_9fa1dc1b-78fe-4b40-b768-d95d3fe81ddc.wav
-Audio Length: 4.98 seconds
-Transcript: Kind of if you are not No. You have to actually put it on this.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:14:53.656548
-Filename: asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_e788beda-21c7-481a-9e90-38ac97625815.wav
-Full Path: ./audio_files\asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_e788beda-21c7-481a-9e90-38ac97625815.wav
-Audio Length: 1.94 seconds
-Transcript: Tell me a story.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:15:09.218794
-Filename: asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_8afec574-c896-4df4-b598-f884f114b62f.wav
-Full Path: ./audio_files\asr_base_58880620-be02-415e-b9a9-bcecd6fcd85b_8afec574-c896-4df4-b598-f884f114b62f.wav
-Audio Length: 2.76 seconds
-Transcript: Tell me another one.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:53:06.340526
-Filename: asr_base_0b3c7f51-e480-4c3b-b84d-d2d4277eb4b3_b509dc72-fe00-43e1-9c9a-c931fbd963ef.wav
-Full Path: ./audio_files\asr_base_0b3c7f51-e480-4c3b-b84d-d2d4277eb4b3_b509dc72-fe00-43e1-9c9a-c931fbd963ef.wav
-Audio Length: 2.76 seconds
-Transcript: Am I audible?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:56:41.965296
-Filename: asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_b842c092-57d8-458b-b164-f5ea18e4b316.wav
-Full Path: ./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_b842c092-57d8-458b-b164-f5ea18e4b316.wav
-Audio Length: 1.98 seconds
-Transcript: Am I audible?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:58:17.158189
-Filename: asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_408be9af-083f-429e-a676-72ddfaffcf09.wav
-Full Path: ./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_408be9af-083f-429e-a676-72ddfaffcf09.wav
-Audio Length: 5.20 seconds
-Transcript: I'm ready. Can you listen to me right now? Can you stay?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:58:36.504023
-Filename: asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_cb30e24f-2082-42e3-b03f-6a237530ba28.wav
-Full Path: ./audio_files\asr_base_a7c9e7b1-df3c-4fd3-bdf7-21378e716d7a_cb30e24f-2082-42e3-b03f-6a237530ba28.wav
-Audio Length: 3.36 seconds
-Transcript: Can you tell me a story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T12:59:52.294534
-Filename: asr_base_65833e66-8628-436b-a1ab-5ef493febef1_c1b8553d-3e73-47ba-81bb-11679a5be488.wav
-Full Path: ./audio_files\asr_base_65833e66-8628-436b-a1ab-5ef493febef1_c1b8553d-3e73-47ba-81bb-11679a5be488.wav
-Audio Length: 1.70 seconds
-Transcript: Hello?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:00:33.801714
-Filename: asr_base_65833e66-8628-436b-a1ab-5ef493febef1_b5015d16-c659-4984-82f8-101e49d031ce.wav
-Full Path: ./audio_files\asr_base_65833e66-8628-436b-a1ab-5ef493febef1_b5015d16-c659-4984-82f8-101e49d031ce.wav
-Audio Length: 4.68 seconds
-Transcript: Six piece tenders.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:04:29.337836
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_b46ec7a7-ff6b-48e6-bbb3-274db4db1300.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_b46ec7a7-ff6b-48e6-bbb3-274db4db1300.wav
-Audio Length: 1.66 seconds
-Transcript: Hello?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:04:56.848487
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_324df0a4-836e-41de-9ac4-fbfc24ec5197.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_324df0a4-836e-41de-9ac4-fbfc24ec5197.wav
-Audio Length: 3.08 seconds
-Transcript: Can you tell me a story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:05:28.819407
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_35baa6c2-5acf-439c-84e5-a0b887f6fc79.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_35baa6c2-5acf-439c-84e5-a0b887f6fc79.wav
-Audio Length: 2.40 seconds
-Transcript: Am I audible to you?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:05:55.601465
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_423b075b-41c0-4707-97bd-496226f53232.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_423b075b-41c0-4707-97bd-496226f53232.wav
-Audio Length: 2.82 seconds
-Transcript: Can you tell me another story?
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:06:26.820176
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_8973e288-43cf-4d09-8391-7dc7a38cf925.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_8973e288-43cf-4d09-8391-7dc7a38cf925.wav
-Audio Length: 2.44 seconds
-Transcript: Can I take ten minutes
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:06:52.279831
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_a4f22978-8e8a-4dab-9445-823cb70aaff1.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_a4f22978-8e8a-4dab-9445-823cb70aaff1.wav
-Audio Length: 2.52 seconds
-Transcript: Check the method right now.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T13:07:18.552938
-Filename: asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_5804d339-f4df-4446-afaa-17cde0720cb8.wav
-Full Path: ./audio_files\asr_base_02ff5dcc-e069-4ca5-8aef-7fa8988136a2_5804d339-f4df-4446-afaa-17cde0720cb8.wav
-Audio Length: 2.42 seconds
-Transcript: Yeah. That's it.
-================================================================================
-
-================================================================================
-Timestamp: 2025-08-21T18:24:29.872528
-Filename: asr_base_72063402-293b-4944-bdf2-6e41b632f775_86a46d2c-5282-4b0e-a95b-6d503e948565.wav
-Full Path: ./audio_files\asr_base_72063402-293b-4944-bdf2-6e41b632f775_86a46d2c-5282-4b0e-a95b-6d503e948565.wav
-Audio Length: 3.96 seconds
-Transcript: Very important. And every day, it's still not clear.
-================================================================================
diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py
index a63a11e7c..b1ff71f76 100644
--- a/main/xiaozhi-server/client.py
+++ b/main/xiaozhi-server/client.py
@@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
-SERVER_IP = "192.168.1.111" # !!! UPDATE with your server's local IP address !!!
-OTA_PORT = 8003
-MQTT_BROKER_HOST = "192.168.1.111" # MQTT gateway IP
+SERVER_IP = "192.168.1.179" # !!! UPDATE with your server's local IP address !!!
+OTA_PORT = 8002
+MQTT_BROKER_HOST = "192.168.1.179" # MQTT gateway IP
MQTT_BROKER_PORT = 1883
@@ -331,7 +331,11 @@ class TestClient:
headers = {"device-id": self.device_mac_formatted}
data = {
"application": {
- "version": "1.0.0"
+ "version": "1.7.6",
+ "name": "DOIT AI Kit v1.7.6"
+ },
+ "board": {
+ "type": "doit-ai-01-kit"
},
"client_id": session_client_id
}
diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py
index b1a2ba850..3a31e4e45 100644
--- a/main/xiaozhi-server/core/providers/asr/openai.py
+++ b/main/xiaozhi-server/core/providers/asr/openai.py
@@ -13,10 +13,12 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
+ super().__init__(config) # Initialize the parent class with asr_filter
self.interface_type = InterfaceType.NON_STREAM
self.api_key = config.get("api_key")
self.api_url = config.get("base_url")
self.model = config.get("model_name")
+ self.language = config.get("language") # Add language support
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
@@ -41,10 +43,14 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}",
}
- # Use data parameter to pass model name
+ # Use data parameter to pass model name and language
data = {
"model": self.model
}
+
+ # Add language parameter if specified
+ if self.language:
+ data["language"] = self.language
# Use with statement to ensure file is closed
with open(file_path, "rb") as audio_file:
diff --git a/main/xiaozhi-server/core/providers/asr/openai_streaming.py b/main/xiaozhi-server/core/providers/asr/openai_streaming.py
new file mode 100644
index 000000000..ba8d75446
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/asr/openai_streaming.py
@@ -0,0 +1,312 @@
+import time
+import asyncio
+import threading
+from typing import Optional, Tuple, List, Callable
+from collections import deque
+from config.logger import setup_logging
+from core.providers.asr.dto.dto import InterfaceType
+from core.providers.asr.base import ASRProviderBase
+import requests
+import io
+import wave
+
+TAG = __name__
+logger = setup_logging()
+
+
+class ASRProvider(ASRProviderBase):
+ """
+ Streaming OpenAI ASR Provider with chunked audio processing
+ Processes audio in chunks for near real-time transcription
+ """
+
+ def __init__(self, config: dict, delete_audio_file: bool):
+ super().__init__(config)
+ self.interface_type = InterfaceType.STREAM
+ self.api_key = config.get("api_key")
+ self.api_url = config.get("api_url", "https://api.openai.com/v1/audio/transcriptions")
+ self.model = config.get("model_name", "whisper-1")
+ self.language = config.get("language", "en")
+ self.output_dir = config.get("output_dir", "tmp/")
+ self.delete_audio_file = delete_audio_file
+
+ # Streaming configuration
+ self.chunk_duration = config.get("chunk_duration", 3.0) # seconds
+ self.overlap_duration = config.get("overlap_duration", 0.5) # seconds for word boundary
+ self.sample_rate = config.get("sample_rate", 16000)
+ self.channels = config.get("channels", 1)
+
+ # Audio buffering
+ self.audio_buffer = deque()
+ self.chunk_size = int(self.chunk_duration * self.sample_rate * 2 * self.channels) # 16-bit samples
+ self.overlap_size = int(self.overlap_duration * self.sample_rate * 2 * self.channels)
+
+ # Threading for async processing
+ self.processing_queue = asyncio.Queue()
+ self.result_callbacks = []
+ self.is_streaming = False
+ self.session_id = None
+
+ logger.bind(tag=TAG).info(f"Streaming ASR initialized - chunk: {self.chunk_duration}s, overlap: {self.overlap_duration}s")
+
+ async def start_streaming(self, session_id: str, callback: Callable[[str, bool], None]) -> bool:
+ """
+ Start streaming transcription session
+
+ Args:
+ session_id: Unique session identifier
+ callback: Function to call with partial results (text, is_final)
+
+ Returns:
+ bool: True if streaming started successfully
+ """
+ try:
+ self.session_id = session_id
+ self.is_streaming = True
+ self.result_callbacks.append(callback)
+
+ # Start processing task
+ asyncio.create_task(self._process_chunks())
+
+ logger.bind(tag=TAG).info(f"Started streaming ASR for session: {session_id}")
+ return True
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to start streaming: {str(e)}")
+ return False
+
+ async def add_audio_chunk(self, audio_data: bytes) -> None:
+ """
+ Add audio data to processing buffer
+
+ Args:
+ audio_data: Raw PCM audio bytes (16-bit, mono/stereo)
+ """
+ if not self.is_streaming:
+ return
+
+ self.audio_buffer.extend(audio_data)
+
+ # Check if we have enough data for a chunk
+ if len(self.audio_buffer) >= self.chunk_size:
+ await self._extract_and_queue_chunk()
+
+ async def _extract_and_queue_chunk(self) -> None:
+ """Extract a chunk from buffer and queue for processing"""
+ if len(self.audio_buffer) < self.chunk_size:
+ return
+
+ # Extract chunk with overlap for previous chunk
+ chunk_data = bytes(list(self.audio_buffer)[:self.chunk_size])
+
+ # Remove processed data but keep overlap
+ for _ in range(self.chunk_size - self.overlap_size):
+ if self.audio_buffer:
+ self.audio_buffer.popleft()
+
+ # Queue chunk for processing
+ await self.processing_queue.put({
+ 'data': chunk_data,
+ 'timestamp': time.time(),
+ 'session_id': self.session_id
+ })
+
+ async def _process_chunks(self) -> None:
+ """Background task to process audio chunks"""
+ while self.is_streaming:
+ try:
+ # Wait for chunk with timeout
+ chunk = await asyncio.wait_for(
+ self.processing_queue.get(),
+ timeout=1.0
+ )
+
+ # Process chunk asynchronously
+ asyncio.create_task(self._transcribe_chunk(chunk))
+
+ except asyncio.TimeoutError:
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Chunk processing error: {str(e)}")
+
+ async def _transcribe_chunk(self, chunk: dict) -> None:
+ """
+ Transcribe a single audio chunk
+
+ Args:
+ chunk: Dict containing audio data and metadata
+ """
+ try:
+ start_time = time.time()
+
+ # Convert PCM to WAV format for OpenAI API
+ wav_data = self._pcm_to_wav(chunk['data'])
+
+ # Prepare API request
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ }
+
+ files = {
+ 'file': ('chunk.wav', wav_data, 'audio/wav'),
+ 'model': (None, self.model),
+ 'response_format': (None, 'json'),
+ 'language': (None, self.language)
+ }
+
+ # Make async request (using thread pool to avoid blocking)
+ loop = asyncio.get_event_loop()
+ response = await loop.run_in_executor(
+ None,
+ lambda: requests.post(self.api_url, headers=headers, files=files, timeout=10)
+ )
+
+ if response.status_code == 200:
+ result = response.json()
+ text = result.get('text', '').strip()
+
+ if text:
+ # Call all registered callbacks with partial result
+ for callback in self.result_callbacks:
+ await self._safe_callback(callback, text, False)
+
+ process_time = time.time() - start_time
+ logger.bind(tag=TAG).debug(
+ f"Chunk transcribed: '{text}' (took {process_time:.2f}s)"
+ )
+ else:
+ logger.bind(tag=TAG).error(
+ f"API error {response.status_code}: {response.text}"
+ )
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Chunk transcription error: {str(e)}")
+
+ async def _safe_callback(self, callback: Callable, text: str, is_final: bool) -> None:
+ """Safely execute callback without blocking"""
+ try:
+ if asyncio.iscoroutinefunction(callback):
+ await callback(text, is_final)
+ else:
+ callback(text, is_final)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Callback error: {str(e)}")
+
+ def _pcm_to_wav(self, pcm_data: bytes) -> io.BytesIO:
+ """
+ Convert PCM data to WAV format
+
+ Args:
+ pcm_data: Raw PCM audio bytes
+
+ Returns:
+ BytesIO: WAV formatted audio data
+ """
+ wav_buffer = io.BytesIO()
+
+ with wave.open(wav_buffer, 'wb') as wav_file:
+ wav_file.setnchannels(self.channels)
+ wav_file.setsampwidth(2) # 16-bit
+ wav_file.setframerate(self.sample_rate)
+ wav_file.writeframes(pcm_data)
+
+ wav_buffer.seek(0)
+ return wav_buffer
+
+ async def finalize_streaming(self, final_callback: Optional[Callable[[str], None]] = None) -> str:
+ """
+ Finalize streaming session and get complete transcript
+
+ Args:
+ final_callback: Optional callback for final complete transcript
+
+ Returns:
+ str: Complete final transcript
+ """
+ try:
+ self.is_streaming = False
+
+ # Process any remaining audio in buffer
+ if len(self.audio_buffer) > 0:
+ remaining_data = bytes(self.audio_buffer)
+ if len(remaining_data) > self.sample_rate: # At least 0.5 seconds
+ final_chunk = {
+ 'data': remaining_data,
+ 'timestamp': time.time(),
+ 'session_id': self.session_id
+ }
+ await self._transcribe_chunk(final_chunk)
+
+ # Clear buffers
+ self.audio_buffer.clear()
+
+ # Wait a moment for final processing
+ await asyncio.sleep(0.5)
+
+ # Notify callbacks that streaming is complete
+ for callback in self.result_callbacks:
+ await self._safe_callback(callback, "", True)
+
+ self.result_callbacks.clear()
+
+ logger.bind(tag=TAG).info(f"Streaming finalized for session: {self.session_id}")
+ return "Streaming session completed"
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Finalization error: {str(e)}")
+ return ""
+
+ async def speech_to_text(self, opus_data: List[bytes], session_id: str, audio_format="opus") -> Tuple[Optional[str], Optional[str]]:
+ """
+ Legacy compatibility method - converts to streaming mode
+
+ Args:
+ opus_data: List of audio chunks
+ session_id: Session identifier
+ audio_format: Audio format
+
+ Returns:
+ Tuple of (transcript, file_path)
+ """
+ try:
+ # Convert opus to PCM if needed
+ if audio_format == "opus":
+ pcm_data = self.decode_opus(opus_data)
+ else:
+ pcm_data = b''.join(opus_data) if isinstance(opus_data, list) else opus_data
+
+ # Process as streaming chunks
+ results = []
+
+ def collect_result(text: str, is_final: bool):
+ if text.strip():
+ results.append(text.strip())
+
+ await self.start_streaming(session_id, collect_result)
+
+ # Add all audio data
+ await self.add_audio_chunk(pcm_data)
+
+ # Finalize and get results
+ await self.finalize_streaming()
+
+ # Combine results
+ final_text = ' '.join(results) if results else ""
+
+ logger.bind(tag=TAG).info(f"Legacy mode completed: '{final_text}'")
+ return final_text, None
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Legacy speech_to_text error: {str(e)}")
+ return None, None
+
+ def get_streaming_stats(self) -> dict:
+ """Get streaming performance statistics"""
+ return {
+ "is_streaming": self.is_streaming,
+ "buffer_size": len(self.audio_buffer),
+ "chunk_duration": self.chunk_duration,
+ "overlap_duration": self.overlap_duration,
+ "queue_size": self.processing_queue.qsize() if hasattr(self.processing_queue, 'qsize') else 0,
+ "active_callbacks": len(self.result_callbacks)
+ }
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/tts/gemini.py b/main/xiaozhi-server/core/providers/tts/gemini.py
new file mode 100644
index 000000000..472a38ffe
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/gemini.py
@@ -0,0 +1,114 @@
+import requests
+import base64
+import wave
+import io
+from core.utils.util import check_model_key
+from core.providers.tts.base import TTSProviderBase
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+
+class TTSProvider(TTSProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__(config, delete_audio_file)
+ self.api_key = config.get("api_key")
+ self.api_url = config.get(
+ "api_url", "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent")
+ self.model = config.get("model", "gemini-2.5-flash-preview-tts")
+ self.voice_name = config.get("voice", "Zephyr")
+ self.language = config.get("language", "en")
+ self.audio_file_type = "wav"
+ self.output_file = config.get("output_dir", "tmp/")
+
+ model_key_msg = check_model_key("TTS", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
+
+ async def text_to_speak(self, text, output_file):
+ headers = {
+ "x-goog-api-key": self.api_key,
+ "Content-Type": "application/json",
+ }
+
+ data = {
+ "contents": [
+ {
+ "parts": [
+ {
+ "text": text
+ }
+ ]
+ }
+ ],
+ "generationConfig": {
+ "responseModalities": ["AUDIO"],
+ "speechConfig": {
+ "voiceConfig": {
+ "prebuiltVoiceConfig": {
+ "voiceName": self.voice_name
+ }
+ }
+ }
+ }
+ }
+
+ try:
+ logger.bind(tag=TAG).debug(f"Gemini TTS request: {data}")
+ response = requests.post(self.api_url, json=data, headers=headers)
+ logger.bind(tag=TAG).debug(f"Gemini TTS response status: {response.status_code}")
+
+ if response.status_code == 200:
+ response_json = response.json()
+
+ # Extract audio data from the response
+ if "candidates" in response_json and len(response_json["candidates"]) > 0:
+ candidate = response_json["candidates"][0]
+ if "content" in candidate and "parts" in candidate["content"]:
+ for part in candidate["content"]["parts"]:
+ if "inlineData" in part and "data" in part["inlineData"]:
+ # Decode base64 audio data
+ audio_data = base64.b64decode(part["inlineData"]["data"])
+
+ # Convert PCM to WAV format
+ wav_data = self._pcm_to_wav(audio_data)
+
+ if output_file:
+ with open(output_file, "wb") as audio_file:
+ audio_file.write(wav_data)
+ else:
+ return wav_data
+ return
+
+ raise Exception("No audio data found in response")
+ else:
+ raise Exception(
+ f"Gemini TTS request failed: {response.status_code} - {response.text}"
+ )
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Gemini TTS failed: {e}")
+ raise
+
+ def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
+ """Convert PCM data to WAV format"""
+ if len(pcm_data) == 0:
+ logger.bind(tag=TAG).warning("PCM data is empty, cannot convert to WAV")
+ return b""
+
+ # Create WAV file header for Gemini's 24kHz, 16-bit, mono PCM
+ wav_buffer = io.BytesIO()
+ try:
+ with wave.open(wav_buffer, 'wb') as wav_file:
+ wav_file.setnchannels(1) # Mono
+ wav_file.setsampwidth(2) # 16-bit
+ wav_file.setframerate(24000) # 24kHz sample rate (Gemini default)
+ wav_file.writeframes(pcm_data)
+
+ wav_buffer.seek(0)
+ wav_data = wav_buffer.read()
+ return wav_data
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
+ return b""
\ No newline at end of file
diff --git a/main/xiaozhi-server/music/Kannada/metadata.json b/main/xiaozhi-server/music/Kannada/metadata.json
index 5b189f2bd..7201abfce 100644
--- a/main/xiaozhi-server/music/Kannada/metadata.json
+++ b/main/xiaozhi-server/music/Kannada/metadata.json
@@ -5,6 +5,7 @@
"alternatives": [
"Aane banthondu Aane",
"aane banthondu aane",
+ "ಆನೆ ಬಂತೊಂದು ಆನೆ",
"elephant came elephant",
"elephant song",
"kannada elephant song",
@@ -18,6 +19,7 @@
"alternatives": [
"Indu Mangalavara",
"indu mangalavara",
+ "ಇಂದು ಮಂಗಳವಾರ",
"tuesday song",
"days of week",
"kannada days song",
@@ -31,6 +33,7 @@
"alternatives": [
"Kothi Mattu Bale Hannu Haadu",
"kothi mattu bale hannu",
+ "ಕೋತಿ ಮತ್ತು ಬಾಳೆ ಹಣ್ಣು ಹಾಡು",
"monkey and banana song",
"monkey banana",
"kannada monkey song",
@@ -44,6 +47,7 @@
"alternatives": [
"Namma Maneyali",
"namma maneyali",
+ "ನಮ್ಮ ಮನೆಯಲ್ಲಿ",
"our house",
"home song",
"kannada home song",
@@ -57,6 +61,7 @@
"alternatives": [
"Nanna Hasu Nanna Hasu",
"nanna hasu",
+ "ನನ್ನ ಹಸು ನನ್ನ ಹಸು",
"my cow my cow",
"cow song",
"kannada cow song",
@@ -70,6 +75,7 @@
"alternatives": [
"Nayi mari Nayi mari Tindi beke",
"nayi mari tindi beke",
+ "ನಾಯಿ ಮರಿ ನಾಯಿ ಮರಿ ತಿಂಡಿ ಬೇಕೆ",
"dog wants food",
"hungry dog",
"kannada dog song",
@@ -83,6 +89,7 @@
"alternatives": [
"Thotake Hogu Timma",
"thotake hogu timma",
+ "ತೋಟಕೆ ಹೋಗು ತಿಮ್ಮ",
"go to garden timma",
"garden song",
"kannada garden song",
diff --git a/main/xiaozhi-server/performance_tester.py b/main/xiaozhi-server/performance_tester.py
deleted file mode 100644
index b07feb42a..000000000
--- a/main/xiaozhi-server/performance_tester.py
+++ /dev/null
@@ -1,674 +0,0 @@
-import asyncio
-import logging
-import os
-import statistics
-import time
-from typing import Dict
-import aiohttp
-from tabulate import tabulate
-from config.settings import load_config
-from core.utils.asr import create_instance as create_stt_instance
-from core.utils.llm import create_instance as create_llm_instance
-from core.utils.tts import create_instance as create_tts_instance
-
-# Set global log level to WARNING, suppress INFO level logs
-logging.basicConfig(level=logging.WARNING)
-
-
-class AsyncPerformanceTester:
- def __init__(self):
- self.config = load_config()
- self.test_sentences = self.config.get("module_test", {}).get(
- "test_sentences",
- [
- "Hello, please introduce yourself",
- "What's the weather like today?",
- "Please summarize the basic principles and application prospects of quantum computing in 100 words",
- ],
- )
-
- self.test_wav_list = []
- self.wav_root = r"config/assets"
- for file_name in os.listdir(self.wav_root):
- file_path = os.path.join(self.wav_root, file_name)
- # Check if file size is larger than 300KB
- if os.path.getsize(file_path) > 300 * 1024: # 300KB = 300 * 1024 bytes
- with open(file_path, "rb") as f:
- self.test_wav_list.append(f.read())
-
- self.results = {"llm": {}, "tts": {}, "stt": {}, "combinations": []}
-
- async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
- """Asynchronously check Ollama service status"""
- async with aiohttp.ClientSession() as session:
- try:
- # Check if service is available
- async with session.get(f"{base_url}/api/version") as response:
- if response.status != 200:
- print(
- f"🚫 Ollama service not started or inaccessible: {base_url}")
- return False
-
- # Check if model exists
- async with session.get(f"{base_url}/api/tags") as response:
- if response.status == 200:
- data = await response.json()
- models = data.get("models", [])
- if not any(model["name"] == model_name for model in models):
- print(
- f"🚫 Ollama model {model_name} not found, please use ollama pull {model_name} to download first"
- )
- return False
- else:
- print(f"🚫 Unable to get Ollama model list")
- return False
-
- return True
- except Exception as e:
- print(f"🚫 Unable to connect to Ollama service: {str(e)}")
- return False
-
- async def _test_tts(self, tts_name: str, config: Dict) -> Dict:
- """Asynchronously test single TTS performance"""
- try:
- logging.getLogger("core.providers.tts.base").setLevel(
- logging.WARNING)
- token_fields = ["access_token", "api_key", "token"]
- if any(
- field in config
- and any(x in config[field] for x in ["你的", "placeholder"])
- for field in token_fields
- ):
- print(
- f"⏭️ TTS {tts_name} access_token/api_key not configured, skipped")
- return {"name": tts_name, "type": "tts", "errors": 1}
-
- module_type = config.get("type", tts_name)
- tts = create_tts_instance(
- module_type, config, delete_audio_file=True)
-
- print(f"🎵 Testing TTS: {tts_name}")
- tmp_file = tts.generate_filename()
- await tts.text_to_speak("Connection test", tmp_file)
-
- if not tmp_file or not os.path.exists(tmp_file):
- print(f"❌ {tts_name} connection failed")
- return {"name": tts_name, "type": "tts", "errors": 1}
-
- total_time = 0
- test_count = len(self.test_sentences[:2])
-
- for i, sentence in enumerate(self.test_sentences[:2], 1):
- start = time.time()
- tmp_file = tts.generate_filename()
- await tts.text_to_speak(sentence, tmp_file)
- duration = time.time() - start
- total_time += duration
-
- if tmp_file and os.path.exists(tmp_file):
- print(f"✓ {tts_name} [{i}/{test_count}]")
- else:
- print(f"✗ {tts_name} [{i}/{test_count}]")
- return {"name": tts_name, "type": "tts", "errors": 1}
-
- return {
- "name": tts_name,
- "type": "tts",
- "avg_time": total_time / test_count,
- "errors": 0,
- }
-
- except Exception as e:
- print(f"⚠️ {tts_name} test failed: {str(e)}")
- return {"name": tts_name, "type": "tts", "errors": 1}
-
- async def _test_stt(self, stt_name: str, config: Dict) -> Dict:
- """Asynchronously test single STT performance"""
- try:
- logging.getLogger("core.providers.asr.base").setLevel(
- logging.WARNING)
- token_fields = ["access_token", "api_key", "token"]
- if any(
- field in config
- and any(x in config[field] for x in ["你的", "placeholder"])
- for field in token_fields
- ):
- print(
- f"⏭️ STT {stt_name} access_token/api_key not configured, skipped")
- return {"name": stt_name, "type": "stt", "errors": 1}
-
- module_type = config.get("type", stt_name)
- stt = create_stt_instance(
- module_type, config, delete_audio_file=True)
- stt.audio_format = "pcm"
-
- print(f"🎵 Testing STT: {stt_name}")
- text, _ = await stt.speech_to_text(
- [self.test_wav_list[0]], "1", stt.audio_format
- )
-
- if text is None:
- print(f"❌ {stt_name} connection failed")
- return {"name": stt_name, "type": "stt", "errors": 1}
-
- total_time = 0
- test_count = len(self.test_wav_list)
-
- for i, sentence in enumerate(self.test_wav_list, 1):
- start = time.time()
- text, _ = await stt.speech_to_text([sentence], "1", stt.audio_format)
- duration = time.time() - start
- total_time += duration
-
- if text:
- print(f"✓ {stt_name} [{i}/{test_count}]")
- else:
- print(f"✗ {stt_name} [{i}/{test_count}]")
- return {"name": stt_name, "type": "stt", "errors": 1}
-
- return {
- "name": stt_name,
- "type": "stt",
- "avg_time": total_time / test_count,
- "errors": 0,
- }
-
- except Exception as e:
- print(f"⚠️ {stt_name} test failed: {str(e)}")
- return {"name": stt_name, "type": "stt", "errors": 1}
-
- async def _test_llm(self, llm_name: str, config: Dict) -> Dict:
- """Asynchronously test single LLM performance"""
- try:
- # For Ollama, skip api_key check and perform special handling
- if llm_name == "Ollama":
- base_url = config.get("base_url", "http://localhost:11434")
- model_name = config.get("model_name")
- if not model_name:
- print(f"🚫 Ollama model_name not configured")
- return {"name": llm_name, "type": "llm", "errors": 1}
-
- if not await self._check_ollama_service(base_url, model_name):
- return {"name": llm_name, "type": "llm", "errors": 1}
- else:
- if "api_key" in config and any(
- x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
- ):
- print(f"🚫 Skipping unconfigured LLM: {llm_name}")
- return {"name": llm_name, "type": "llm", "errors": 1}
-
- # Get actual type (compatible with old configuration)
- module_type = config.get("type", llm_name)
- llm = create_llm_instance(module_type, config)
-
- # Uniformly use UTF-8 encoding
- test_sentences = [
- s.encode("utf-8").decode("utf-8") for s in self.test_sentences
- ]
-
- # Create test tasks for all sentences
- sentence_tasks = []
- for sentence in test_sentences:
- sentence_tasks.append(
- self._test_single_sentence(llm_name, llm, sentence)
- )
-
- # Execute all sentence tests concurrently
- sentence_results = await asyncio.gather(*sentence_tasks)
-
- # Process results
- valid_results = [r for r in sentence_results if r is not None]
- if not valid_results:
- print(
- f"⚠️ {llm_name} no valid data, configuration may be incorrect")
- return {"name": llm_name, "type": "llm", "errors": 1}
-
- first_token_times = [r["first_token_time"] for r in valid_results]
- response_times = [r["response_time"] for r in valid_results]
-
- # Filter abnormal data
- mean = statistics.mean(response_times)
- stdev = statistics.stdev(response_times) if len(
- response_times) > 1 else 0
- filtered_times = [
- t for t in response_times if t <= mean + 3 * stdev]
-
- if len(filtered_times) < len(test_sentences) * 0.5:
- print(
- f"⚠️ {llm_name} insufficient valid data, network may be unstable")
- return {"name": llm_name, "type": "llm", "errors": 1}
-
- return {
- "name": llm_name,
- "type": "llm",
- "avg_response": sum(response_times) / len(response_times),
- "avg_first_token": sum(first_token_times) / len(first_token_times),
- "std_first_token": (
- statistics.stdev(first_token_times)
- if len(first_token_times) > 1
- else 0
- ),
- "std_response": (
- statistics.stdev(response_times) if len(
- response_times) > 1 else 0
- ),
- "errors": 0,
- }
-
- except Exception as e:
- print(f"LLM {llm_name} test failed: {str(e)}")
- return {"name": llm_name, "type": "llm", "errors": 1}
-
- async def _test_single_sentence(self, llm_name: str, llm, sentence: str) -> Dict:
- """Test performance of a single sentence"""
- try:
- print(f"📝 {llm_name} starting test: {sentence[:20]}...")
- sentence_start = time.time()
- first_token_received = False
- first_token_time = None
-
- async def process_response():
- nonlocal first_token_received, first_token_time
- for chunk in llm.response(
- "perf_test", [{"role": "user", "content": sentence}]
- ):
- if not first_token_received and chunk.strip() != "":
- first_token_time = time.time() - sentence_start
- first_token_received = True
- print(
- f"✓ {llm_name} first token: {first_token_time:.3f}s")
- yield chunk
-
- response_chunks = []
- async for chunk in process_response():
- response_chunks.append(chunk)
-
- response_time = time.time() - sentence_start
- print(f"✓ {llm_name} response completed: {response_time:.3f}s")
-
- if first_token_time is None:
- first_token_time = (
- response_time # If no first token detected, use total response time
- )
-
- return {
- "name": llm_name,
- "type": "llm",
- "first_token_time": first_token_time,
- "response_time": response_time,
- }
-
- except Exception as e:
- print(f"⚠️ {llm_name} sentence test failed: {str(e)}")
- return None
-
- def _generate_combinations(self):
- """Generate best combination recommendations"""
- valid_llms = [
- k
- for k, v in self.results["llm"].items()
- if v["errors"] == 0 and v["avg_first_token"] >= 0.05
- ]
- valid_tts = [k for k, v in self.results["tts"].items()
- if v["errors"] == 0]
- valid_stt = [k for k, v in self.results["stt"].items()
- if v["errors"] == 0]
-
- # Find benchmark values
- min_first_token = (
- min([self.results["llm"][llm]["avg_first_token"]
- for llm in valid_llms])
- if valid_llms
- else 1
- )
- min_tts_time = (
- min([self.results["tts"][tts]["avg_time"] for tts in valid_tts])
- if valid_tts
- else 1
- )
- min_stt_time = (
- min([self.results["stt"][stt]["avg_time"] for stt in valid_stt])
- if valid_stt
- else 1
- )
-
- for llm in valid_llms:
- for tts in valid_tts:
- for stt in valid_stt:
- # Calculate relative performance score (smaller is better)
- llm_score = (
- self.results["llm"][llm]["avg_first_token"] /
- min_first_token
- )
- tts_score = self.results["tts"][tts]["avg_time"] / \
- min_tts_time
- stt_score = self.results["stt"][stt]["avg_time"] / \
- min_stt_time
-
- # Calculate stability score (standard deviation/average, smaller is more stable)
- llm_stability = (
- self.results["llm"][llm]["std_first_token"]
- / self.results["llm"][llm]["avg_first_token"]
- )
-
- # Comprehensive score (considering performance and stability)
- # LLM score: performance weight(70%) + stability weight(30%)
- llm_final_score = llm_score * 0.7 + llm_stability * 0.3
-
- # Total score = LLM score(70%) + TTS score(30%) + STT score(30%)
- total_score = (
- llm_final_score * 0.7 + tts_score * 0.3 + stt_score * 0.3
- )
-
- self.results["combinations"].append(
- {
- "llm": llm,
- "tts": tts,
- "stt": stt,
- "score": total_score,
- "details": {
- "llm_first_token": self.results["llm"][llm][
- "avg_first_token"
- ],
- "llm_stability": llm_stability,
- "tts_time": self.results["tts"][tts]["avg_time"],
- "stt_time": self.results["stt"][stt]["avg_time"],
- },
- }
- )
-
- # Smaller score is better
- self.results["combinations"].sort(key=lambda x: x["score"])
-
- def _print_results(self):
- """Print test results"""
- llm_table = []
- for name, data in self.results["llm"].items():
- if data["errors"] == 0:
- stability = data["std_first_token"] / data["avg_first_token"]
- llm_table.append(
- [
- name, # No need for fixed width, let tabulate handle alignment
- f"{data['avg_first_token']:.3f}s",
- f"{data['avg_response']:.3f}s",
- f"{stability:.3f}",
- ]
- )
-
- if llm_table:
- print("\nLLM Performance Rankings:\n")
- print(
- tabulate(
- llm_table,
- headers=["Model Name", "First Token Time",
- "Total Time", "Stability"],
- tablefmt="github",
- colalign=("left", "right", "right", "right"),
- disable_numparse=True,
- )
- )
- else:
- print("\n⚠️ No available LLM modules for testing.")
-
- tts_table = []
- for name, data in self.results["tts"].items():
- if data["errors"] == 0:
- # No need for fixed width
- tts_table.append([name, f"{data['avg_time']:.3f}s"])
-
- if tts_table:
- print("\nTTS Performance Rankings:\n")
- print(
- tabulate(
- tts_table,
- headers=["Model Name", "Synthesis Time"],
- tablefmt="github",
- colalign=("left", "right"),
- disable_numparse=True,
- )
- )
- else:
- print("\n⚠️ No available TTS modules for testing.")
-
- stt_table = []
- for name, data in self.results["stt"].items():
- if data["errors"] == 0:
- # No need for fixed width
- stt_table.append([name, f"{data['avg_time']:.3f}s"])
-
- if stt_table:
- print("\nSTT Performance Rankings:\n")
- print(
- tabulate(
- stt_table,
- headers=["Model Name", "Recognition Time"],
- tablefmt="github",
- colalign=("left", "right"),
- disable_numparse=True,
- )
- )
- else:
- print("\n⚠️ No available STT modules for testing.")
-
- if self.results["combinations"]:
- print("\nRecommended Configuration Combinations (smaller score is better):\n")
- combo_table = []
- for combo in self.results["combinations"][:5]:
- combo_table.append(
- [
- # No need for fixed width
- f"{combo['llm']} + {combo['tts']} + {combo['stt']}",
- f"{combo['score']:.3f}",
- f"{combo['details']['llm_first_token']:.3f}s",
- f"{combo['details']['llm_stability']:.3f}",
- f"{combo['details']['tts_time']:.3f}s",
- f"{combo['details']['stt_time']:.3f}s",
- ]
- )
-
- print(
- tabulate(
- combo_table,
- headers=[
- "Combination Plan",
- "Comprehensive Score",
- "LLM First Token Time",
- "Stability",
- "TTS Synthesis Time",
- "STT Recognition Time",
- ],
- tablefmt="github",
- colalign=("left", "right", "right",
- "right", "right", "right"),
- disable_numparse=True,
- )
- )
- else:
- print("\n⚠️ No available module combination recommendations.")
-
- def _process_results(self, all_results):
- """Process test results"""
- for result in all_results:
- if result["errors"] == 0:
- if result["type"] == "llm":
- self.results["llm"][result["name"]] = result
- elif result["type"] == "tts":
- self.results["tts"][result["name"]] = result
- elif result["type"] == "stt":
- self.results["stt"][result["name"]] = result
- else:
- pass
-
- async def run(self):
- """Execute full asynchronous testing"""
- print("🔍 Starting to filter available modules...")
-
- # Create all test tasks
- all_tasks = []
-
- # LLM test tasks
- if self.config.get("LLM") is not None:
- for llm_name, config in self.config.get("LLM", {}).items():
- # Check configuration validity
- if llm_name == "CozeLLM":
- if any(x in config.get("bot_id", "") for x in ["你的"]) or any(
- x in config.get("user_id", "") for x in ["你的"]
- ):
- print(
- f"⏭️ LLM {llm_name} bot_id/user_id not configured, skipped")
- continue
- elif "api_key" in config and any(
- x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
- ):
- print(f"⏭️ LLM {llm_name} api_key not configured, skipped")
- continue
-
- # For Ollama, check service status first
- if llm_name == "Ollama":
- base_url = config.get("base_url", "http://localhost:11434")
- model_name = config.get("model_name")
- if not model_name:
- print(f"🚫 Ollama model_name not configured")
- continue
-
- if not await self._check_ollama_service(base_url, model_name):
- continue
-
- print(f"📋 Adding LLM test task: {llm_name}")
- module_type = config.get("type", llm_name)
- llm = create_llm_instance(module_type, config)
-
- # Create independent tasks for each sentence
- for sentence in self.test_sentences:
- sentence = sentence.encode("utf-8").decode("utf-8")
- all_tasks.append(
- self._test_single_sentence(llm_name, llm, sentence)
- )
-
- # TTS test tasks
- if self.config.get("TTS") is not None:
- for tts_name, config in self.config.get("TTS", {}).items():
- token_fields = ["access_token", "api_key", "token"]
- if any(
- field in config
- and any(x in config[field] for x in ["你的", "placeholder"])
- for field in token_fields
- ):
- print(
- f"⏭️ TTS {tts_name} access_token/api_key not configured, skipped")
- continue
-
- print(f"🎵 Adding TTS test task: {tts_name}")
- all_tasks.append(self._test_tts(tts_name, config))
-
- # STT test tasks
- if len(self.test_wav_list) >= 1:
- if self.config.get("ASR") is not None:
- for stt_name, config in self.config.get("ASR", {}).items():
- token_fields = ["access_token", "api_key", "token"]
- if any(
- field in config
- and any(x in config[field] for x in ["你的", "placeholder"])
- for field in token_fields
- ):
- print(
- f"⏭️ ASR {stt_name} access_token/api_key not configured, skipped")
- continue
-
- print(f"🎵 Adding ASR test task: {stt_name}")
- all_tasks.append(self._test_stt(stt_name, config))
- else:
- print(
- f"\n⚠️ No audio files found in {self.wav_root} path, STT test tasks skipped")
-
- print(
- f"\n✅ Found {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} available LLM modules"
- )
- print(
- f"✅ Found {len([t for t in all_tasks if '_test_tts' in str(t)])} available TTS modules"
- )
- print(
- f"✅ Found {len([t for t in all_tasks if '_test_stt' in str(t)])} available STT modules"
- )
-
- print("\n⏳ Starting concurrent testing of all modules...\n")
-
- # Execute all test tasks concurrently
- all_results = await asyncio.gather(*all_tasks, return_exceptions=True)
-
- # Process LLM results
- llm_results = {}
- for result in [
- r
- for r in all_results
- if r and isinstance(r, dict) and r.get("type") == "llm"
- ]:
- llm_name = result["name"]
- if llm_name not in llm_results:
- llm_results[llm_name] = {
- "name": llm_name,
- "type": "llm",
- "first_token_times": [],
- "response_times": [],
- "errors": 0,
- }
-
- llm_results[llm_name]["first_token_times"].append(
- result["first_token_time"]
- )
- llm_results[llm_name]["response_times"].append(
- result["response_time"])
-
- # Calculate LLM averages and standard deviations
- for llm_name, data in llm_results.items():
- if len(data["first_token_times"]) >= len(self.test_sentences) * 0.5:
- self.results["llm"][llm_name] = {
- "name": llm_name,
- "type": "llm",
- "avg_response": sum(data["response_times"])
- / len(data["response_times"]),
- "avg_first_token": sum(data["first_token_times"])
- / len(data["first_token_times"]),
- "std_first_token": (
- statistics.stdev(data["first_token_times"])
- if len(data["first_token_times"]) > 1
- else 0
- ),
- "std_response": (
- statistics.stdev(data["response_times"])
- if len(data["response_times"]) > 1
- else 0
- ),
- "errors": 0,
- }
-
- # Process TTS results
- for result in [
- r
- for r in all_results
- if r and isinstance(r, dict) and r.get("type") == "tts"
- ]:
- if result["errors"] == 0:
- self.results["tts"][result["name"]] = result
-
- # Process STT results
- for result in [
- r
- for r in all_results
- if r and isinstance(r, dict) and r.get("type") == "stt"
- ]:
- if result["errors"] == 0:
- self.results["stt"][result["name"]] = result
-
- # Generate combination recommendations and print results
- print("\n📊 Generating test report...")
- self._generate_combinations()
- self._print_results()
-
-
-async def main():
- tester = AsyncPerformanceTester()
- await tester.run()
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/main/xiaozhi-server/performance_tester_vllm.py b/main/xiaozhi-server/performance_tester_vllm.py
deleted file mode 100644
index d49843ae5..000000000
--- a/main/xiaozhi-server/performance_tester_vllm.py
+++ /dev/null
@@ -1,199 +0,0 @@
-import time
-import asyncio
-import logging
-import statistics
-import base64
-from typing import Dict
-from tabulate import tabulate
-from config.settings import load_config
-from core.utils.vllm import create_instance
-
-# Set global log level to WARNING, suppress INFO level logs
-logging.basicConfig(level=logging.WARNING)
-
-
-class AsyncVisionPerformanceTester:
- def __init__(self):
- self.config = load_config()
- self.test_images = [
- "../../docs/images/demo1.png",
- "../../docs/images/demo2.png",
- ]
- self.test_questions = [
- "What's in this image?",
- "Please describe the content of this image in detail",
- ]
-
- # Load test images
- self.results = {"vllm": {}}
-
- async def _test_vllm(self, vllm_name: str, config: Dict) -> Dict:
- """Asynchronously test single vision large model performance"""
- try:
- # Check API key configuration
- if "api_key" in config and any(
- x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
- ):
- print(f"⏭️ VLLM {vllm_name} api_key not configured, skipped")
- return {"name": vllm_name, "type": "vllm", "errors": 1}
-
- # Get actual type (compatible with old configuration)
- module_type = config.get("type", vllm_name)
- vllm = create_instance(module_type, config)
-
- print(f"🖼️ Testing VLLM: {vllm_name}")
-
- # Create all test tasks
- test_tasks = []
- for question in self.test_questions:
- for image in self.test_images:
- test_tasks.append(
- self._test_single_vision(
- vllm_name, vllm, question, image)
- )
-
- # Execute all tests concurrently
- test_results = await asyncio.gather(*test_tasks)
-
- # Process results
- valid_results = [r for r in test_results if r is not None]
- if not valid_results:
- print(
- f"⚠️ {vllm_name} no valid data, configuration may be incorrect")
- return {"name": vllm_name, "type": "vllm", "errors": 1}
-
- response_times = [r["response_time"] for r in valid_results]
-
- # Filter abnormal data
- mean = statistics.mean(response_times)
- stdev = statistics.stdev(response_times) if len(
- response_times) > 1 else 0
- filtered_times = [
- t for t in response_times if t <= mean + 3 * stdev]
-
- if len(filtered_times) < len(test_tasks) * 0.5:
- print(
- f"⚠️ {vllm_name} insufficient valid data, network may be unstable")
- return {"name": vllm_name, "type": "vllm", "errors": 1}
-
- return {
- "name": vllm_name,
- "type": "vllm",
- "avg_response": sum(response_times) / len(response_times),
- "std_response": (
- statistics.stdev(response_times) if len(
- response_times) > 1 else 0
- ),
- "errors": 0,
- }
-
- except Exception as e:
- print(f"⚠️ VLLM {vllm_name} test failed: {str(e)}")
- return {"name": vllm_name, "type": "vllm", "errors": 1}
-
- async def _test_single_vision(
- self, vllm_name: str, vllm, question: str, image: str
- ) -> Dict:
- """Test performance of a single vision question"""
- try:
- print(f"📝 {vllm_name} starting test: {question[:20]}...")
- start_time = time.time()
-
- # Read image and convert to base64
- with open(image, "rb") as image_file:
- image_data = image_file.read()
- image_base64 = base64.b64encode(image_data).decode("utf-8")
-
- # Get response directly
- response = vllm.response(question, image_base64)
- response_time = time.time() - start_time
-
- print(f"✓ {vllm_name} response completed: {response_time:.3f}s")
-
- return {
- "name": vllm_name,
- "type": "vllm",
- "response_time": response_time,
- }
-
- except Exception as e:
- print(f"⚠️ {vllm_name} test failed: {str(e)}")
- return None
-
- def _print_results(self):
- """Print test results"""
- vllm_table = []
- for name, data in self.results["vllm"].items():
- if data["errors"] == 0:
- stability = data["std_response"] / data["avg_response"]
- vllm_table.append(
- [
- name,
- f"{data['avg_response']:.3f}s",
- f"{stability:.3f}",
- ]
- )
-
- if vllm_table:
- print("\nVision Large Model Performance Rankings:\n")
- print(
- tabulate(
- vllm_table,
- headers=["Model Name", "Response Time", "Stability"],
- tablefmt="github",
- colalign=("left", "right", "right"),
- disable_numparse=True,
- )
- )
- else:
- print("\n⚠️ No available vision large models for testing.")
-
- async def run(self):
- """Execute full asynchronous testing"""
- print("🔍 Starting to filter available vision large models...")
-
- if not self.test_images:
- print(f"\n⚠️ No image files found in path, testing cannot proceed")
- return
-
- # Create all test tasks
- all_tasks = []
-
- # VLLM test tasks
- if self.config.get("VLLM") is not None:
- for vllm_name, config in self.config.get("VLLM", {}).items():
- if "api_key" in config and any(
- x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
- ):
- print(
- f"⏭️ VLLM {vllm_name} api_key not configured, skipped")
- continue
-
- print(f"🖼️ Adding VLLM test task: {vllm_name}")
- all_tasks.append(self._test_vllm(vllm_name, config))
-
- print(f"\n✅ Found {len(all_tasks)} available vision large models")
- print(f"✅ Using {len(self.test_images)} test images")
- print(f"✅ Using {len(self.test_questions)} test questions")
-
- print("\n⏳ Starting concurrent testing of all models...\n")
-
- # Execute all test tasks concurrently
- all_results = await asyncio.gather(*all_tasks, return_exceptions=True)
-
- # Process results
- for result in all_results:
- if isinstance(result, dict) and result["errors"] == 0:
- self.results["vllm"][result["name"]] = result
-
- # Print results
- print("\n📊 Generating test report...")
- self._print_results()
-
-
-async def main():
- tester = AsyncVisionPerformanceTester()
- await tester.run()
-
-if __name__ == "__main__":
- asyncio.run(main())