Spaces:
Sleeping
Sleeping
Upload tts.py
Browse files
tts.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from gtts import gTTS
|
2 |
+
from typing import Dict, Any
|
3 |
+
import re
|
4 |
+
from deep_translator import GoogleTranslator
|
5 |
+
import io
|
6 |
+
|
7 |
+
class TextToSpeechConverter:
|
8 |
+
def __init__(self):
|
9 |
+
pass
|
10 |
+
|
11 |
+
def clean_text_for_tts(self, text: str) -> str:
|
12 |
+
text = re.sub(r'http\S+', '', text)
|
13 |
+
text = re.sub(r'[^\w\s.,?!;:\-\'"()]', ' ', text)
|
14 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
15 |
+
return text
|
16 |
+
|
17 |
+
def translate_to_hindi(self, text: str) -> str:
|
18 |
+
try:
|
19 |
+
hindi_text = GoogleTranslator(source='auto', target='hi').translate(text)
|
20 |
+
return hindi_text
|
21 |
+
except Exception as e:
|
22 |
+
print(f"Translation error: {e}")
|
23 |
+
return "अनुवाद में त्रुटि हुई। कृपया पुनः प्रयास करें।"
|
24 |
+
|
25 |
+
def generate_speech(self, text: str) -> Dict[str, Any]:
|
26 |
+
try:
|
27 |
+
cleaned_text = self.clean_text_for_tts(text)
|
28 |
+
hindi_text = self.translate_to_hindi(cleaned_text)
|
29 |
+
tts = gTTS(text=hindi_text, lang='hi', slow=False)
|
30 |
+
audio_buffer = io.BytesIO()
|
31 |
+
tts.write_to_fp(audio_buffer)
|
32 |
+
audio_buffer.seek(0)
|
33 |
+
return {
|
34 |
+
"success": True,
|
35 |
+
"message": "Speech generated successfully",
|
36 |
+
"audio_buffer": audio_buffer,
|
37 |
+
"hindi_text": hindi_text
|
38 |
+
}
|
39 |
+
except Exception as e:
|
40 |
+
print(f"Error generating speech: {str(e)}")
|
41 |
+
return {
|
42 |
+
"success": False,
|
43 |
+
"message": f"Error generating speech: {str(e)}",
|
44 |
+
"audio_buffer": None,
|
45 |
+
"hindi_text": None
|
46 |
+
}
|