Local-Voice/fix_cache.py
2025-09-23 13:40:57 +08:00

149 lines
4.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复现有缓存问题的脚本
用于处理文件名中的冒号和索引问题
"""
import os
import sys
import json
import shutil
from pathlib import Path
from greeting_cache_manager import GreetingCacheManager
def fix_existing_cache():
"""修复现有的缓存问题"""
print("🔧 修复现有缓存问题")
print("=" * 50)
cache_dir = Path("greeting_cache")
if not cache_dir.exists():
print("❌ 缓存目录不存在,无需修复")
return
# 1. 备份当前缓存目录
backup_dir = Path("greeting_cache_backup")
if backup_dir.exists():
shutil.rmtree(backup_dir)
shutil.copytree(cache_dir, backup_dir)
print(f"✅ 已备份当前缓存到: {backup_dir}")
# 2. 修复文件名中的冒号问题
print("\n🔍 修复文件名中的冒号问题...")
problem_files = list(cache_dir.glob(":*.wav"))
fixed_count = 0
for file in problem_files:
new_name = file.name[1:] # 移除开头的冒号
new_path = file.parent / new_name
try:
file.rename(new_path)
print(f" ✅ 重命名: {file.name} -> {new_name}")
fixed_count += 1
except Exception as e:
print(f" ❌ 重命名失败: {file.name} - {e}")
print(f"📊 修复了 {fixed_count} 个文件名")
# 3. 重建缓存索引
print("\n🔄 重建缓存索引...")
cache_manager = GreetingCacheManager()
# 清空当前索引
cache_manager.cache_index = {}
# 扫描所有wav文件
wav_files = list(cache_dir.glob("*.wav"))
print(f"🔍 扫描到 {len(wav_files)} 个wav文件")
for wav_file in wav_files:
# 尝试从文件名解析角色名和hash
name_parts = wav_file.stem.split('_')
if len(name_parts) >= 2:
character_name = name_parts[0]
greeting_hash = name_parts[-1] # 最后一个部分是hash
cache_key = f"{character_name}_{greeting_hash}"
cache_manager.cache_index[cache_key] = str(wav_file.resolve())
print(f" ✅ 添加到索引: {character_name} -> {wav_file.name}")
else:
print(f" ❌ 无法解析文件名: {wav_file.name}")
# 保存索引
cache_manager._save_cache_index()
print(f"✅ 索引重建完成,共 {len(cache_manager.cache_index)} 条记录")
# 4. 验证缓存完整性
print(f"\n🔍 验证缓存完整性...")
valid_count, invalid_count = cache_manager.validate_cache()
print(f" 有效缓存: {valid_count}")
print(f" 无效缓存: {invalid_count}")
# 5. 测试缓存访问
print(f"\n🧪 测试缓存访问...")
# 尝试从角色配置文件获取测试数据
characters_dir = Path("characters")
if characters_dir.exists():
char_files = list(characters_dir.glob("*.json"))
for char_file in char_files[:3]: # 测试前3个角色
try:
with open(char_file, 'r', encoding='utf-8') as f:
char_config = json.load(f)
character_name = char_file.stem
greeting_text = char_config.get("greeting", "")
if greeting_text:
is_cached = cache_manager.is_cached(character_name, greeting_text)
cached_path = cache_manager.get_cached_audio_path(character_name, greeting_text)
print(f" {character_name}: {'' if is_cached else ''} 缓存")
if cached_path:
print(f" 路径: {Path(cached_path).name}")
except Exception as e:
print(f" ❌ 测试角色 {char_file.name} 失败: {e}")
print(f"\n🎉 缓存修复完成!")
# 6. 提供使用建议
print(f"\n💡 使用建议:")
print(f" 1. 如果仍有问题,可以删除缓存目录重新生成")
print(f" 2. 确保greeting_cache目录有写入权限")
print(f" 3. 检查磁盘空间是否充足")
print(f" 4. 重启应用程序以应用修复")
def clean_cache_directory():
"""清理缓存目录"""
print("\n🧹 清理缓存目录")
print("=" * 50)
cache_dir = Path("greeting_cache")
if cache_dir.exists():
try:
shutil.rmtree(cache_dir)
print(f"✅ 已删除缓存目录: {cache_dir}")
except Exception as e:
print(f"❌ 删除缓存目录失败: {e}")
else:
print("✅ 缓存目录不存在,无需清理")
if __name__ == "__main__":
try:
if len(sys.argv) > 1 and sys.argv[1] == "clean":
clean_cache_directory()
else:
fix_existing_cache()
except Exception as e:
print(f"\n❌ 修复失败: {e}")
import traceback
traceback.print_exc()
sys.exit(1)