File size: 1,956 Bytes
4cded81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
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