File size: 9,638 Bytes
9d29c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# audio_generator.py - V273.0 (Google Cloud TTS - High Quality Hebrew)
import asyncio
import base64
import os
import tempfile
import logging

# Configure Logging
logger = logging.getLogger(__name__)

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐ŸŽ™๏ธ Google Cloud TTS Configuration
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# 
# ืงื•ืœื•ืช ืขื‘ืจื™ื™ื ื–ืžื™ื ื™ื:
# - he-IL-Wavenet-A (ื ืงื‘ื”, ืื™ื›ื•ืช ื’ื‘ื•ื”ื”) โญ ืžื•ืžืœืฅ
# - he-IL-Wavenet-B (ื–ื›ืจ, ืื™ื›ื•ืช ื’ื‘ื•ื”ื”)
# - he-IL-Standard-A (ื ืงื‘ื”, ืื™ื›ื•ืช ืจื’ื™ืœื”)
# - he-IL-Standard-B (ื–ื›ืจ, ืื™ื›ื•ืช ืจื’ื™ืœื”)
#
# Free Tier: 1 ืžื™ืœื™ื•ืŸ ืชื•ื•ื™ื/ื—ื•ื“ืฉ (WaveNet: 1M, Standard: 4M)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

GOOGLE_VOICE_NAME = "he-IL-Wavenet-A"  # Female, high quality
GOOGLE_LANGUAGE_CODE = "he-IL"
SPEAKING_RATE = 0.95  # ืžืขื˜ ื™ื•ืชืจ ืื™ื˜ื™ ืœื‘ื”ื™ืจื•ืช
PITCH = 1.0  # ื’ื•ื‘ื” ืงื•ืœ ืจื’ื™ืœ

# Fallback to edge-tts if Google Cloud not configured
USE_EDGE_TTS_FALLBACK = True
EDGE_TTS_VOICE = "he-IL-HilaNeural"

from firebase_manager import firebase_manager  # V261.17


def _is_google_cloud_configured() -> bool:
    """ื‘ื“ื™ืงื” ืื Google Cloud ืžื•ื’ื“ืจ"""
    # Option 1: Environment variable
    if os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
        return True
    # Option 2: Check for credentials file in common locations
    common_paths = [
        "/app/google-credentials.json",
        "./google-credentials.json",
        os.path.expanduser("~/.config/gcloud/application_default_credentials.json")
    ]
    for path in common_paths:
        if os.path.exists(path):
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path
            return True
    return False


async def _generate_with_google_cloud(text: str, output_path: str) -> bool:
    """
    ื™ืฆื™ืจืช ืื•ื“ื™ื• ืขื Google Cloud TTS
    ืžื—ื–ื™ืจ True ืื ื”ืฆืœื™ื—, False ืื ื ื›ืฉืœ
    """
    try:
        from google.cloud import texttospeech
        
        # Create client
        client = texttospeech.TextToSpeechClient()
        
        # Build the voice request
        voice = texttospeech.VoiceSelectionParams(
            language_code=GOOGLE_LANGUAGE_CODE,
            name=GOOGLE_VOICE_NAME,
        )
        
        # Select the audio format
        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3,
            speaking_rate=SPEAKING_RATE,
            pitch=PITCH,
        )
        
        # Build the synthesis input
        synthesis_input = texttospeech.SynthesisInput(text=text)
        
        # Perform the text-to-speech request
        logger.info(f"๐ŸŽ™๏ธ Google Cloud TTS: Generating audio for {len(text)} chars...")
        
        # Run in thread pool to not block async
        loop = asyncio.get_running_loop()
        response = await loop.run_in_executor(
            None,
            lambda: client.synthesize_speech(
                input=synthesis_input,
                voice=voice,
                audio_config=audio_config
            )
        )
        
        # Write the audio content to file
        with open(output_path, "wb") as out:
            out.write(response.audio_content)
        
        logger.info(f"โœ… Google Cloud TTS: Audio saved to {output_path}")
        return True
        
    except ImportError:
        logger.warning("โš ๏ธ google-cloud-texttospeech not installed. Run: pip install google-cloud-texttospeech")
        return False
    except Exception as e:
        logger.error(f"โŒ Google Cloud TTS failed: {e}")
        return False


async def _generate_with_edge_tts(text: str, output_path: str) -> bool:
    """
    ื™ืฆื™ืจืช ืื•ื“ื™ื• ืขื edge-tts (Fallback)
    """
    try:
        import edge_tts
        
        logger.info(f"๐ŸŽ™๏ธ Edge TTS (Fallback): Generating audio...")
        communicate = edge_tts.Communicate(text, EDGE_TTS_VOICE)
        await communicate.save(output_path)
        
        logger.info(f"โœ… Edge TTS: Audio saved to {output_path}")
        return True
        
    except Exception as e:
        logger.error(f"โŒ Edge TTS failed: {e}")
        return False


async def generate_teacher_audio(text: str, output_path: str = None) -> str:
    """
    V273.0: ื™ืฆื™ืจืช ืื•ื“ื™ื• ืขื Google Cloud TTS (ืื™ื›ื•ืช ื’ื‘ื•ื”ื”)
    
    ืžื ืกื” ืงื•ื“ื Google Cloud TTS, ืื ืœื ืžื•ื’ื“ืจ/ื ื›ืฉืœ โ†’ edge-tts fallback
    
    Returns: 
        - Public URL (if Firebase upload success)
        - Base64 string (fallback)
        - None (if all failed)
    """
    try:
        if not text:
            return None
        
        # Clean text for TTS (remove emojis and special chars that cause issues)
        clean_text = _clean_text_for_tts(text)
        
        if not clean_text:
            return None
            
        logger.info(f"๐ŸŽ™๏ธ TTS Request: {clean_text[:50]}...")
        
        # Determine output path
        if output_path:
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            final_path = output_path
        else:
            timestamp = int(asyncio.get_event_loop().time() * 1000)
            final_path = os.path.join(tempfile.gettempdir(), f"audio_{timestamp}.mp3")

        # Try Google Cloud TTS first
        success = False
        if _is_google_cloud_configured():
            success = await _generate_with_google_cloud(clean_text, final_path)
        else:
            logger.info("โ„น๏ธ Google Cloud not configured, using Edge TTS")
        
        # Fallback to edge-tts
        if not success and USE_EDGE_TTS_FALLBACK:
            success = await _generate_with_edge_tts(clean_text, final_path)
        
        if not success:
            logger.error("โŒ All TTS methods failed")
            return None

        # Try Firebase Upload
        try:
            blob_name = f"audio/{os.path.basename(final_path)}"
            loop = asyncio.get_running_loop()
            
            public_url = await loop.run_in_executor(
                None, 
                lambda: firebase_manager.upload_file(final_path, blob_name)
            )
            
            if public_url:
                logger.info(f"โ˜๏ธ Firebase URL: {public_url}")
                # Clean up local file
                if not output_path:
                    os.remove(final_path)
                return public_url
        except Exception as fb_err:
            logger.warning(f"โš ๏ธ Firebase upload failed ({fb_err}). Using Base64.")

        # Fallback: Return Base64
        with open(final_path, "rb") as audio_file:
            audio_bytes = audio_file.read()
            audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
            
        # Clean up temp file
        if not output_path:
            os.remove(final_path)
            
        return audio_base64

    except Exception as e:
        logger.error(f"โŒ TTS Generation Failed: {e}")
        return None


def _clean_text_for_tts(text: str) -> str:
    """
    ื ื™ืงื•ื™ ื˜ืงืกื˜ ืœืคื ื™ TTS - ื”ืกืจืช ืื™ืžื•ื’'ื™ื ื•ืกื™ืžื ื™ื ื‘ืขื™ื™ืชื™ื™ื
    """
    import re
    
    if not text:
        return ""
    
    # Remove emojis
    emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags
        u"\U00002702-\U000027B0"
        u"\U000024C2-\U0001F251"
        "]+", flags=re.UNICODE)
    
    clean = emoji_pattern.sub('', text)
    
    # Remove multiple spaces
    clean = re.sub(r'\s+', ' ', clean)
    
    # Remove LaTeX remnants that might have slipped through
    clean = clean.replace('$', '').replace('\\', '')
    
    return clean.strip()


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿงช Testing
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

if __name__ == "__main__":
    async def main():
        text = """
        ืื™ื–ื” ื™ื•ืคื™ ืฉืœ ืชืจื’ื™ืœ! ื”ื™ื™ื ื• ืฆืจื™ื›ื™ื ืœืžืฆื•ื ืืช ื ืงื•ื“ื•ืช ื”ืงื™ืฆื•ืŸ ืฉืœ ื”ืคื•ื ืงืฆื™ื”.
        ื”ืฉืชืžืฉื ื• ื‘ื ื’ื–ืจืช ืจืืฉื•ื ื” ื›ื“ื™ ืœืžืฆื•ื ืื™ืคื” ื”ืฉื™ืคื•ืข ืžืชืืคืก.
        ื”ื˜ืจื™ืง ืœื–ื›ื•ืจ - ื ื’ื–ืจืช ืืคืก ืชืžื™ื“ ืžืกืžื ืช ื ืงื•ื“ืช ืงื™ืฆื•ืŸ ืืคืฉืจื™ืช.
        ื›ืœ ื”ื›ื‘ื•ื“ ืขืœ ื”ื”ืชืžื“ื”!
        """
        
        print(f"๐ŸŽ™๏ธ Testing TTS...")
        print(f"๐Ÿ“ Text length: {len(text)} chars")
        print(f"โ˜๏ธ Google Cloud configured: {_is_google_cloud_configured()}")
        
        result = await generate_teacher_audio(text)
        
        if result:
            if result.startswith("http"):
                print(f"โœ… Got URL: {result}")
            else:
                print(f"โœ… Got Base64: {len(result)} chars")
        else:
            print("โŒ TTS failed")
    
    asyncio.run(main())