Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- cat << 'EOF' > /home/santos/.openclaw/workspace/scripts/jervasio-manual.py
- #!/usr/bin/env python3
- import time, json, subprocess, sys, re, queue, threading
- import numpy as np
- import sounddevice as sd
- import requests
- from faster_whisper import WhisperModel
- # Configurações
- PIPER_EXE = "/home/santos/.openclaw/workspace/jervasio_env/bin/piper"
- PIPER_MODEL = "/home/santos/.openclaw/workspace/models/pt_PT-tugao-medium.onnx"
- WHISPER_MODEL_SIZE = "base"
- RECORD_SECONDS = 6
- GATEWAY_URL = "http://127.0.0.1:18789/v1/responses"
- GATEWAY_TOKEN = "55b6988ba106c77aa19159079166fe0f810fe397bc117f81"
- tts_queue = queue.Queue()
- print("\n🤖 Jervásio: Modelos prontos. À escuta...", flush=True)
- try:
- whisper = WhisperModel(WHISPER_MODEL_SIZE, device="cpu", compute_type="int8")
- except Exception as e:
- print(f"❌ Erro Whisper: {e}", flush=True); sys.exit(1)
- def speak(text):
- t_start = time.time()
- clean_text = text.replace('"', "").replace("\n", " ").replace("*", "").strip()
- if not clean_text:
- return
- cmd = f'echo "{clean_text}" | {PIPER_EXE} --model {PIPER_MODEL} --output_raw | paplay --raw --rate=22050 --channels=1 --format=s16le'
- subprocess.run(cmd, shell=True)
- print(f" ⏱️ [TTS (Piper)]: {time.time() - t_start:.2f}s", flush=True)
- def tts_worker():
- while True:
- chunk = tts_queue.get()
- if chunk is None: break
- try:
- speak(chunk)
- finally:
- tts_queue.task_done()
- threading.Thread(target=tts_worker, daemon=True).start()
- def pop_speakable_chunk(buf: str):
- m = re.search(r"(.+?[.!?;:])(\s|$)", buf, re.S)
- if not m: return None, buf
- chunk = m.group(1).strip()
- rest = buf[m.end():].lstrip()
- return chunk, rest
- def send_via_gateway_stream(text):
- headers = {
- "Authorization": f"Bearer {GATEWAY_TOKEN}",
- "Content-Type": "application/json",
- "x-openclaw-agent-id": "main",
- "x-openclaw-session-key": "agent:main:main",
- "x-openclaw-message-channel": "webchat"
- }
- payload = {"model": "openclaw", "input": text, "stream": True}
- full_text, tts_buffer = "", ""
- event_type, primeira_palavra = None, False
- t_start = time.time()
- print("⏳ A enviar para o Gateway...", flush=True)
- try:
- with requests.post(GATEWAY_URL, headers=headers, json=payload, stream=True) as r:
- r.raise_for_status()
- print("🤖 Jervásio: ", end="", flush=True)
- for line in r.iter_lines(decode_unicode=True):
- if line == "" or line.startswith("event: ") or not line.startswith("data: "):
- continue
- data = line[6:]
- if data == "[DONE]": break
- try:
- obj = json.loads(data)
- delta = obj.get("delta", "")
- if delta:
- if not primeira_palavra:
- print(f"\n ⏱️ [Cérebro TTFT]: {time.time() - t_start:.2f}s", flush=True)
- print("🤖 ", end="", flush=True)
- primeira_palavra = True
- full_text += delta
- tts_buffer += delta
- print(delta, end="", flush=True)
- while True:
- chunk, tts_buffer = pop_speakable_chunk(tts_buffer)
- if not chunk: break
- tts_queue.put(chunk)
- except: pass
- except Exception as e: print(f"\n❌ Erro: {e}")
- if tts_buffer.strip(): tts_queue.put(tts_buffer.strip())
- return full_text.strip()
- while True:
- try:
- input("\n[ ENTER PARA FALAR ]")
- t_rec_start = time.time()
- print(f"🎤 Gravando ({RECORD_SECONDS}s)...", flush=True)
- audio = sd.rec(int(RECORD_SECONDS * 16000), samplerate=16000, channels=1, dtype="float32")
- sd.wait()
- print(f" ⏱️ [Gravação]: {time.time() - t_rec_start:.2f}s", flush=True)
- t_stt_start = time.time()
- segments, _ = whisper.transcribe(np.squeeze(audio), language="pt", initial_prompt="Jervásio")
- user_text = " ".join([s.text for s in segments]).strip()
- print(f" ⏱️ [STT (Whisper)]: {time.time() - t_stt_start:.2f}s", flush=True)
- if user_text:
- print(f"👤 Tu: {user_text}", flush=True)
- send_via_gateway_stream(user_text)
- tts_queue.join()
- except KeyboardInterrupt:
- print("\nAté breve!"); break
- EOF
Advertisement
Add Comment
Please, Sign In to add comment