Files
HeurAMS/legacy/precache_legacy.py
2025-10-11 22:05:25 +08:00

59 lines
1.7 KiB
Python

#!/usr/bin/env python3
# 音频预缓存实用程序(旧版), 独立于主程序之外, 但依赖其他组件
import particles as pt
import auxiliary as aux
import edge_tts as tts
from pathlib import Path
import shutil
import time
def precache(text: str):
"""预缓存单个文本的音频"""
cache_dir = Path("./cache/voice/")
cache_dir.mkdir(parents=True, exist_ok=True)
cache = cache_dir / f"{aux.get_md5(text)}.wav"
if not cache.exists():
communicate = tts.Communicate(text, "zh-CN-XiaoxiaoNeural")
communicate.save_sync(f"./cache/voice/{aux.get_md5(text)}.wav")
def proc_file(path: Path):
"""处理单个文件"""
nu = pt.NucleonUnion(path)
c = 0
for i in nu.nucleons:
c += 1
print(f"预缓存 [{nu.name}] ({c}/{len(nu)}): {i['content'].replace('/', '')}")
precache(i['content'].replace('/', ''))
def walk(path_str: str):
"""遍历目录处理所有文件"""
path = Path(path_str)
print(f"正在遍历目录: {path}")
try:
for item in path.iterdir():
if item.is_file() and item.suffix == ".toml":
print(f"正预缓存文件: {item.name}")
proc_file(item)
elif item.is_dir():
print(f"进入目录: {item.name}")
except:
print("发生一个异常, 于 5 秒后自动重新下载")
time.sleep(5)
walk(path_str)
if __name__ == "__main__":
print("音频预缓存实用程序(旧版)")
print("A: 全部缓存")
print("C: 清空缓存")
choice = input("输入选项 $ ").upper()
if choice == "A":
walk("./nucleon")
elif choice == "C":
shutil.rmtree("./cache/voice", ignore_errors=True)
print("缓存已清空")