Load ChatTTS model and default speaker embedding when the application starts
()
| 61 | |
| 62 | @app.on_event("startup") |
| 63 | async def startup_event(): |
| 64 | """Load ChatTTS model and default speaker embedding when the application starts""" |
| 65 | # Initialize ChatTTS and async lock |
| 66 | app.state.chat = ChatTTS.Chat(get_logger("ChatTTS")) |
| 67 | app.state.model_lock = asyncio.Lock() # Use async lock instead of thread lock |
| 68 | |
| 69 | # Register text normalizers |
| 70 | app.state.chat.normalizer.register("en", normalizer_en_nemo_text()) |
| 71 | app.state.chat.normalizer.register("zh", normalizer_zh_tn()) |
| 72 | |
| 73 | logger.info("Initializing ChatTTS...") |
| 74 | if app.state.chat.load(source="huggingface"): |
| 75 | logger.info("Model loaded successfully.") |
| 76 | else: |
| 77 | logger.error("Model loading failed, exiting application.") |
| 78 | raise RuntimeError("Failed to load ChatTTS model") |
| 79 | |
| 80 | # Load default speaker embedding |
| 81 | # Preload all supported speaker embeddings into memory at startup to avoid repeated loading during runtime |
| 82 | app.state.spk_emb_map = {} |
| 83 | for voice, spk_path in VOICE_MAP.items(): |
| 84 | if os.path.exists(spk_path): |
| 85 | app.state.spk_emb_map[voice] = torch.load( |
| 86 | spk_path, map_location=torch.device("cpu") |
| 87 | ) |
| 88 | logger.info(f"Preloading speaker embedding: {voice} -> {spk_path}") |
| 89 | else: |
| 90 | logger.warning(f"Speaker embedding not found: {spk_path}, skipping preload") |
| 91 | app.state.spk_emb = app.state.spk_emb_map.get("default") # Default embedding |
| 92 | |
| 93 | |
| 94 | # Request parameter whitelist |
nothing calls this directly
no test coverage detected