Local-Voice/test_role_switching.py
2025-09-25 10:41:27 +08:00

147 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
模拟角色切换场景测试缓存功能
"""
import os
import sys
import json
import time
from pathlib import Path
# 添加项目路径
sys.path.append('.')
def simulate_role_switching():
"""模拟角色切换场景"""
print("🎭 模拟角色切换场景测试")
print("=" * 50)
# 模拟角色配置
characters = {
"李白": {
"name": "李白",
"greeting": "吾乃李白,字太白,号青莲居士。今天有幸与君相会,让我们畅谈诗词人生吧!",
"voice": "ICL_zh_male_huzi_v1_tob"
},
"猪八戒": {
"name": "猪八戒",
"greeting": "嘿!俺老猪来也!今天咱聊点啥好吃的?要不要一起去化缘啊?",
"voice": "zh_male_zhubajie_mars_bigtts"
}
}
# 确保缓存目录存在
os.makedirs("greeting_cache", exist_ok=True)
# 模拟多次角色切换
for iteration in range(3):
print(f"\n🔄 第 {iteration + 1} 次角色切换测试")
for character_name, character_config in characters.items():
print(f"\n📝 切换到角色: {character_name}")
# 检查缓存是否存在
cache_path = f"greeting_cache/{character_name}.wav"
cache_exists = os.path.exists(cache_path)
if cache_exists:
print(f" ✅ 找到缓存: {cache_path}")
# 模拟加载缓存
file_size = os.path.getsize(cache_path)
print(f" 📁 缓存文件大小: {file_size} 字节")
print(f" ⚡ 使用缓存播放无需TTS生成")
else:
print(f" ❌ 无缓存需要生成TTS")
print(f" 🎵 模拟TTS生成...")
# 模拟TTS生成延迟
time.sleep(0.1)
# 模拟生成音频数据
mock_audio = f"audio_for_{character_name}".encode('utf-8') + os.urandom(2000)
# 保存到缓存
try:
with open(cache_path, 'wb') as f:
f.write(mock_audio)
print(f" 💾 已保存到缓存: {cache_path}")
print(f" 📊 缓存大小: {len(mock_audio)} 字节")
except Exception as e:
print(f" ❌ 保存缓存失败: {e}")
print(f" 🎵 模拟播放打招呼: {character_config['greeting'][:30]}...")
print(f"{character_name} 打招呼完成")
print(f"\n🎊 角色切换测试完成")
def analyze_cache_performance():
"""分析缓存性能"""
print("\n📊 缓存性能分析")
print("=" * 30)
cache_dir = Path("greeting_cache")
if not cache_dir.exists():
print("❌ 缓存目录不存在")
return
cache_files = list(cache_dir.glob("*.wav"))
if not cache_files:
print("❌ 没有找到缓存文件")
return
total_size = 0
print(f"📁 找到 {len(cache_files)} 个缓存文件:")
for cache_file in cache_files:
file_size = cache_file.stat().st_size
total_size += file_size
character_name = cache_file.stem
print(f" 📄 {character_name}: {file_size} 字节")
print(f"\n📊 缓存统计:")
print(f" 总文件数: {len(cache_files)}")
print(f" 总大小: {total_size} 字节 ({total_size/1024:.1f} KB)")
print(f" 平均大小: {total_size/len(cache_files):.1f} 字节")
def cleanup_cache():
"""清理缓存"""
print("\n🧹 清理缓存")
print("=" * 20)
cache_dir = Path("greeting_cache")
if cache_dir.exists():
for cache_file in cache_dir.glob("*.wav"):
try:
cache_file.unlink()
print(f" 已删除: {cache_file.name}")
except Exception as e:
print(f" 删除失败 {cache_file.name}: {e}")
# 尝试删除空目录
try:
if not any(cache_dir.iterdir()):
cache_dir.rmdir()
print(f" 已删除空目录: {cache_dir}")
except Exception as e:
print(f" 删除目录失败: {e}")
else:
print(" 缓存目录不存在")
if __name__ == "__main__":
print("🚀 开始角色切换场景测试")
try:
# 模拟角色切换
simulate_role_switching()
# 分析缓存性能
analyze_cache_performance()
finally:
# 清理缓存
cleanup_cache()
print("\n🎉 所有测试完成!")