57 lines
2.1 KiB
Python
57 lines
2.1 KiB
Python
import os
|
|
import speech_recognition as sr
|
|
from pydub import AudioSegment
|
|
import uuid
|
|
import re
|
|
import asyncio
|
|
import edge_tts
|
|
|
|
def transcribe_audio(file_path: str) -> str:
|
|
"""Converte áudio (qualquer formato compatível com pydub) para WAV e transcreve com Google Speech."""
|
|
recognizer = sr.Recognizer()
|
|
|
|
# Se não for wav, converte usando pydub (precisa de ffmpeg na VPS)
|
|
temp_wav = f"/tmp/{uuid.uuid4()}.wav"
|
|
try:
|
|
audio = AudioSegment.from_file(file_path)
|
|
audio.export(temp_wav, format="wav")
|
|
|
|
with sr.AudioFile(temp_wav) as source:
|
|
audio_data = recognizer.record(source)
|
|
text = recognizer.recognize_google(audio_data, language="pt-BR")
|
|
return text
|
|
finally:
|
|
if os.path.exists(temp_wav):
|
|
os.remove(temp_wav)
|
|
|
|
async def _edge_tts_gen(text: str, filepath: str):
|
|
"""Gera áudio usando Microsoft Edge TTS (Gratuito e Neural)."""
|
|
# Voz Masculina PT-BR: Antonio ou Donato
|
|
# Rate +20% para ser mais rápido conforme pedido
|
|
voice = "pt-BR-AntonioNeural"
|
|
communicate = edge_tts.Communicate(text, voice, rate="+20%")
|
|
await communicate.save(filepath)
|
|
|
|
def text_to_speech(text: str) -> str:
|
|
"""Sintetiza texto em áudio MP3 usando Edge TTS (Voz Masculina Rápida)."""
|
|
# Limpeza para narração
|
|
texto_limpo = text.replace("🤖", "").replace("🧑🏫", "").replace("*", "").replace("`", "")
|
|
texto_limpo = re.sub(r'<REFINED>.*?</REFINED>', '', texto_limpo, flags=re.DOTALL).strip()
|
|
|
|
if not texto_limpo:
|
|
texto_limpo = "Prompt vazio."
|
|
|
|
filename = f"audio_reply_{uuid.uuid4().hex[:8]}.mp3"
|
|
filepath = os.path.join("/tmp", filename)
|
|
|
|
try:
|
|
# Edge TTS é async, precisamos rodar no loop
|
|
asyncio.run(_edge_tts_gen(texto_limpo, filepath))
|
|
return filename
|
|
except Exception as e:
|
|
print(f"[VOICE] Erro Edge TTS: {e}. Criando arquivo mudo ou ignorando.")
|
|
# Cria um arquivo vazio para não quebrar o retorno
|
|
with open(filepath, "wb") as f:
|
|
f.write(b"")
|
|
return filename
|