Spaces:
Sleeping
Sleeping
| """ | |
| TTS Module - Microsoft Edge TTS | |
| Uses hi-IN-SwaraNeural — natural Hindi female voice. | |
| No compilation needed, works on Python 3.14 + Windows. | |
| No API key required. | |
| Returns (sample_rate, audio_array) tuple — same as existing tts_hindi(). | |
| """ | |
| import edge_tts | |
| import asyncio | |
| import numpy as np | |
| import soundfile as sf | |
| import io | |
| import tempfile | |
| import os | |
| HINDI_VOICE = "hi-IN-SwaraNeural" | |
| def tts_hindi(text: str): | |
| """ | |
| Convert Hindi text to audio using Edge TTS. | |
| Keeps same function signature as existing tts_hindi() in app.py. | |
| Returns (sample_rate, audio_array) tuple or None on failure. | |
| """ | |
| try: | |
| if not text or not text.strip(): | |
| return None | |
| # Limit text length | |
| if len(text) > 500: | |
| text = text[:500] | |
| print("DEBUG TTS: text truncated to 500 chars") | |
| # Edge TTS is async — run it synchronously | |
| async def _generate(): | |
| communicate = edge_tts.Communicate(text, HINDI_VOICE) | |
| # Use tempfile to get a proper temp path | |
| fd, tmp_path = tempfile.mkstemp(suffix=".mp3") | |
| os.close(fd) # Close file descriptor immediately | |
| try: | |
| await communicate.save(tmp_path) | |
| return tmp_path | |
| except Exception as e: | |
| if os.path.exists(tmp_path): | |
| os.remove(tmp_path) | |
| raise e | |
| # Run async function | |
| tmp_path = asyncio.run(_generate()) | |
| # Read audio file | |
| audio_array, sample_rate = sf.read(tmp_path) | |
| audio_array = audio_array.astype(np.float32) | |
| # Cleanup temp file | |
| if os.path.exists(tmp_path): | |
| os.remove(tmp_path) | |
| print(f"DEBUG TTS: generated audio at {sample_rate}Hz") | |
| return (int(sample_rate), audio_array) | |
| except Exception as e: | |
| print(f"TTS error: {e}") | |
| return None | |