Spaces:
Sleeping
Sleeping
File size: 1,703 Bytes
b54ddc8 |
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 |
from gtts import gTTS
from typing import Dict, Any
import re
from deep_translator import GoogleTranslator
import io
class TextToSpeechConverter:
def __init__(self):
pass
def clean_text_for_tts(self, text: str) -> str:
text = re.sub(r'http\S+', '', text)
text = re.sub(r'[^\w\s.,?!;:\-\'"()]', ' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
def translate_to_hindi(self, text: str) -> str:
try:
hindi_text = GoogleTranslator(source='auto', target='hi').translate(text)
return hindi_text
except Exception as e:
print(f"Translation error: {e}")
return "अनुवाद में त्रुटि हुई। कृपया पुनः प्रयास करें।"
def generate_speech(self, text: str) -> Dict[str, Any]:
try:
cleaned_text = self.clean_text_for_tts(text)
hindi_text = self.translate_to_hindi(cleaned_text)
tts = gTTS(text=hindi_text, lang='hi', slow=False)
audio_buffer = io.BytesIO()
tts.write_to_fp(audio_buffer)
audio_buffer.seek(0)
return {
"success": True,
"message": "Speech generated successfully",
"audio_buffer": audio_buffer,
"hindi_text": hindi_text
}
except Exception as e:
print(f"Error generating speech: {str(e)}")
return {
"success": False,
"message": f"Error generating speech: {str(e)}",
"audio_buffer": None,
"hindi_text": None
} |