-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcliente.py
More file actions
143 lines (114 loc) · 3.8 KB
/
cliente.py
File metadata and controls
143 lines (114 loc) · 3.8 KB
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
#!/usr/bin/env python3
"""Cliente de voz con feedback visual: botón -> graba -> backend -> reproduce."""
import subprocess
import tempfile
import os
import sys
import time
import signal
from pathlib import Path
import requests
from gpiozero import Button
from led_states import LEDController
# --- CONFIG ---
BACKEND_URL = "https://web-production-f9d2a.up.railway.app/voice"
MIC_DEVICE = "plughw:CARD=seeed2micvoicec,DEV=0"
SPEAKER_DEVICE = "plughw:CARD=seeed2micvoicec,DEV=0"
BUTTON_PIN = 17
SAMPLE_RATE = 16000
LED_BRIGHTNESS = 15
# --------------
button = Button(BUTTON_PIN, pull_up=True, bounce_time=0.2)
leds = LEDController(brightness=LED_BRIGHTNESS)
def grabar_mientras_apretado(output_path: str):
print("🎙️ Grabando... (soltá el botón para parar)")
leds.set_state("recording")
proc = subprocess.Popen([
"arecord",
"-D", MIC_DEVICE,
"-r", str(SAMPLE_RATE),
"-c", "1",
"-f", "S16_LE",
"-t", "wav",
output_path,
], stderr=subprocess.DEVNULL)
button.wait_for_release()
# SIGINT en vez de SIGTERM para que arecord cierre el WAV correctamente
proc.send_signal(signal.SIGINT)
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.terminate()
proc.wait()
print("⏹️ Grabación terminada.")
def mandar_y_reproducir(audio_path: str):
"""Manda audio al backend, descarga la respuesta mp3 entera, reproduce."""
print("📤 Mandando audio al backend...")
leds.set_state("thinking")
t0 = time.time()
try:
with open(audio_path, "rb") as f:
resp = requests.post(
BACKEND_URL,
files={"audio": ("audio.wav", f, "audio/wav")},
timeout=60,
)
resp.raise_for_status()
elapsed = time.time() - t0
print(f"✅ Audio descargado en {elapsed:.2f}s ({len(resp.content)} bytes)")
leds.set_state("speaking")
# Guardar mp3 a archivo temp y reproducir con mpg123
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
f.write(resp.content)
mp3_path = f.name
try:
subprocess.run(
["mpg123", "-q", "-a", "default", mp3_path],
stderr=subprocess.DEVNULL,
check=True,
)
finally:
os.unlink(mp3_path)
total = time.time() - t0
print(f"⏱️ Round-trip completo: {total:.2f}s")
except requests.exceptions.RequestException as e:
print(f"❌ Error de red: {e}")
leds.set_state("error")
time.sleep(2)
except subprocess.CalledProcessError as e:
print(f"❌ Error reproduciendo: {e}")
leds.set_state("error")
time.sleep(2)
def main():
leds.start()
leds.set_state("idle")
print("=" * 50)
print("Cliente de voz listo (streaming).")
print(f"Backend: {BACKEND_URL}")
print("Apretá y mantené el botón para hablar.")
print("Ctrl+C para salir.")
print("=" * 50)
while True:
button.wait_for_press()
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
audio_path = f.name
try:
grabar_mientras_apretado(audio_path)
size = Path(audio_path).stat().st_size
if size < 1000:
print("⚠️ Grabación muy corta, ignorando.")
leds.set_state("idle")
continue
mandar_y_reproducir(audio_path)
finally:
if os.path.exists(audio_path):
os.unlink(audio_path)
leds.set_state("idle")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nChau.")
finally:
leds.stop()
sys.exit(0)