File size: 3,087 Bytes
1354c32
 
 
 
 
 
 
 
 
 
 
 
 
3d6e8a6
82b3395
3d6e8a6
1354c32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a82806d
 
1354c32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
import numpy as np
from google.cloud import texttospeech as tts
from .utils import setup_gcp_credentials

# --- GCP Credential Setup ---
setup_gcp_credentials()

# --- TTS Client and Configuration ---
try:
    client_tts = tts.TextToSpeechClient()
    voice_name = "th-TH-Chirp3-HD-Vindemiatrix"
    language_code = "-".join(voice_name.split("-")[:2])
    streaming_config = tts.StreamingSynthesizeConfig(
        voice=tts.VoiceSelectionParams(language_code=language_code, name=voice_name),
        streaming_audio_config = tts.StreamingAudioConfig(speaking_rate = 1.10)
        
    )
    print("Google TTS Client initialized.")
except Exception as e:
    client_tts = None
    print(f"Failed to initialize Google TTS Client: {e}")

def _request_generator(text):
    """Generator for TTS streaming requests."""
    yield tts.StreamingSynthesizeRequest(streaming_config=streaming_config)
    yield tts.StreamingSynthesizeRequest(input=tts.StreamingSynthesisInput(text=text))

def synthesize_text(text: str, lang = 'th' , speed = 2.0):
    """
    Synthesizes text using Google Cloud Text-to-Speech streaming synthesis.
    This function yields (sample_rate, audio_chunk) tuples.
    """
    if not client_tts:
        print("TTS client not available. Skipping synthesis.")
        return

    # Clean and preprocess text for better pronunciation
    text = text.translate(str.maketrans('', '', ':*!\"\'()'))
    replacements = {
        '1577': 'หนึ่งห้าเจ็ดเจ็ด', ' 2.': 'สอง.', '/n2.': ' สอง.', ' 3.': ' สาม.', '/n3.': ' สาม.',
        ' 4.': ' สี่.', '/n4.':  ' สี่.', ' 10.': ' สิบ.', '/n10.': ' สิบ.',
        'พ.ศ.': 'พอศอ', '. ': ' ', '-19': ' 19', 'เพื่อยก': 'เพื่อ ยก',
        '√': 'เครื่องหมายติ๊กถูก', '=>': 'จากนั้นเลือก', 'รอกด': 'รอ กด', ' ณ ': ' นะ ',
        '[2ฟรี1]': 'สองฟรีหนึ่ง', "+": 'บวก',  "12X": "สิบสองเอ็กซ์", "12x": "สิบสองเอ็กซ์",'[2ฟร2]': 'สองฟรีสอง'

    }
    for old, new in replacements.items():
        text = text.replace(old, new)
       
    print(f"TTS input text: {text}")

    if text.endswith('.'):
        text = text[:-1]
    

    if not text.strip():
        return

    try:
        responses = client_tts.streaming_synthesize(_request_generator(text))
        
        first_chunk = True
        for response in responses:
            if response.audio_content:
                samples = np.frombuffer(response.audio_content, dtype=np.int16)
                if first_chunk:
                    samples = samples[600:] # Optionally drop start of first chunk
                    first_chunk = False
                yield (24000, samples)
    except Exception as e:
        print(f"Error during TTS synthesis for text '{text}': {e}")

if __name__ == "__main__":
    for a,b in synthesize_text("สวัสดี"):
        print(b)