poly-server 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ """poly-server: detecção do idioma falado e tradução de interfaces para o Poly."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .app import create_app
6
+ from .config import Settings
7
+
8
+ __all__ = ["create_app", "Settings", "__version__"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
poly_server/app.py ADDED
@@ -0,0 +1,210 @@
1
+ """Aplicação FastAPI do poly-server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ from contextlib import asynccontextmanager
9
+ from typing import Callable
10
+
11
+ import numpy as np
12
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.concurrency import run_in_threadpool
15
+ from pydantic import BaseModel, Field
16
+
17
+ from . import __version__
18
+ from .asr import Recognizer, WhisperRecognizer
19
+ from .config import Settings
20
+ from .events import EventHub
21
+ from .listening import ListeningController
22
+ from .translate import ArgosTranslator, CachedTranslator, Translator, UnsupportedLanguagePair
23
+ from .vad import Segmenter, pcm16_to_float32
24
+
25
+ log = logging.getLogger("poly_server")
26
+
27
+
28
+ class TranslateRequest(BaseModel):
29
+ source_lang: str = "en"
30
+ target_lang: str
31
+ texts: dict[str, str] = Field(default_factory=dict)
32
+
33
+
34
+ class TranslateResponse(BaseModel):
35
+ target_lang: str
36
+ texts: dict[str, str]
37
+
38
+
39
+ def create_app(
40
+ settings: Settings | None = None,
41
+ *,
42
+ recognizer: Recognizer | None = None,
43
+ translator: Translator | None = None,
44
+ segmenter_factory: Callable[[], Segmenter] | None = None,
45
+ ) -> FastAPI:
46
+ """
47
+ Cria o app. `recognizer`, `translator` e `segmenter_factory` podem ser
48
+ trocados (testes, outro motor de tradução, outro modelo de voz).
49
+ """
50
+ settings = settings or Settings.from_env()
51
+ recognizer = recognizer or WhisperRecognizer(
52
+ settings.whisper_model,
53
+ device=settings.whisper_device,
54
+ compute_type=settings.whisper_compute_type,
55
+ download_root=settings.cache_dir / "whisper",
56
+ )
57
+ translator = translator or CachedTranslator(
58
+ ArgosTranslator(auto_download=settings.auto_download),
59
+ settings.cache_dir / "translations.sqlite",
60
+ )
61
+
62
+ def make_segmenter() -> Segmenter:
63
+ if segmenter_factory:
64
+ return segmenter_factory()
65
+ return Segmenter(
66
+ vad_mode=settings.vad_mode,
67
+ frame_ms=settings.frame_ms,
68
+ pre_roll_ms=settings.pre_roll_ms,
69
+ start_trigger_ms=settings.start_trigger_ms,
70
+ end_trigger_ms=settings.end_trigger_ms,
71
+ max_utterance_sec=settings.max_utterance_sec,
72
+ )
73
+
74
+ hub = EventHub()
75
+ state = {"mic": False}
76
+
77
+ controller = ListeningController(make_segmenter(), recognizer.recognize, hub.publish)
78
+
79
+ @asynccontextmanager
80
+ async def lifespan(app: FastAPI):
81
+ hub.bind(asyncio.get_running_loop())
82
+ mic = None
83
+ if settings.mic:
84
+ from .mic import MicSource
85
+
86
+ try:
87
+ mic = MicSource(controller.feed, device=settings.mic_device)
88
+ mic.start()
89
+ state["mic"] = True
90
+ except RuntimeError as e:
91
+ log.warning("%s Continuing without local microphone.", e)
92
+ yield
93
+ if mic:
94
+ mic.stop()
95
+
96
+ app = FastAPI(title="poly-server", version=__version__, lifespan=lifespan)
97
+ app.add_middleware(
98
+ CORSMiddleware,
99
+ allow_origins=settings.cors_origins,
100
+ allow_methods=["*"],
101
+ allow_headers=["*"],
102
+ )
103
+
104
+ @app.get("/health")
105
+ def health():
106
+ return {"ok": True, "version": __version__, "mic": state["mic"]}
107
+
108
+ @app.post("/i18n/auto-translate", response_model=TranslateResponse)
109
+ def auto_translate(req: TranslateRequest):
110
+ keys = list(req.texts.keys())
111
+ try:
112
+ values = translator.translate_many([req.texts[k] for k in keys], req.source_lang, req.target_lang)
113
+ except UnsupportedLanguagePair as e:
114
+ raise HTTPException(
115
+ status_code=422,
116
+ detail={
117
+ "code": "unsupported_language_pair",
118
+ "source": e.source,
119
+ "target": e.target,
120
+ "message": str(e),
121
+ },
122
+ ) from e
123
+ return TranslateResponse(target_lang=req.target_lang, texts=dict(zip(keys, values)))
124
+
125
+ @app.websocket("/ws")
126
+ async def events(ws: WebSocket):
127
+ """
128
+ Eventos do microfone local, para todos os clientes. Comandos aceitos:
129
+ {"type": "config", "listening": "manual"} e
130
+ {"type": "listen", "action": "start" | "stop"}.
131
+ """
132
+ await ws.accept()
133
+ q = hub.subscribe()
134
+ manual = False
135
+
136
+ async def send_events():
137
+ while True:
138
+ await ws.send_json(await q.get())
139
+
140
+ async def receive_commands():
141
+ nonlocal manual
142
+ while True:
143
+ msg = await ws.receive_json()
144
+ kind = msg.get("type")
145
+ if kind == "config" and msg.get("listening") == "manual" and not manual:
146
+ manual = True
147
+ controller.add_manual_client()
148
+ await ws.send_json({"type": "listening", "listening": controller.listening})
149
+ elif kind == "listen" and msg.get("action") == "start":
150
+ await run_in_threadpool(controller.start)
151
+ elif kind == "listen" and msg.get("action") == "stop":
152
+ await run_in_threadpool(controller.stop)
153
+
154
+ tasks = [asyncio.create_task(send_events()), asyncio.create_task(receive_commands())]
155
+ try:
156
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
157
+ for t in done:
158
+ if t.exception() and not isinstance(t.exception(), WebSocketDisconnect):
159
+ log.warning("ws: %s", t.exception())
160
+ finally:
161
+ for t in tasks:
162
+ t.cancel()
163
+ hub.unsubscribe(q)
164
+ if manual:
165
+ controller.remove_manual_client()
166
+
167
+ @app.websocket("/ws/audio")
168
+ async def audio(ws: WebSocket):
169
+ """
170
+ Áudio vindo do navegador: mensagens binárias com PCM 16-bit little
171
+ endian, mono, 16 kHz. Os eventos de reconhecimento voltam só para
172
+ este cliente: {"type": "speech_start"} quando a fala começa e
173
+ {"type": "utterance_end"} quando termina, antes do reconhecimento. Mensagens de texto: {"type": "flush"} reconhece a fala em
174
+ andamento (botão "parar"); {"type": "reset"} descarta o áudio.
175
+ """
176
+ await ws.accept()
177
+ segmenter = make_segmenter()
178
+
179
+ async def recognize_and_send(utterance: np.ndarray) -> None:
180
+ result = await run_in_threadpool(recognizer.recognize, utterance)
181
+ await ws.send_json(result.to_event())
182
+
183
+ try:
184
+ while True:
185
+ msg = await ws.receive()
186
+ if msg["type"] == "websocket.disconnect":
187
+ break
188
+ if msg.get("bytes") is not None:
189
+ was_speaking = segmenter.in_speech
190
+ utterances = segmenter.feed(pcm16_to_float32(msg["bytes"]))
191
+ if not was_speaking and (segmenter.in_speech or utterances):
192
+ await ws.send_json({"type": "speech_start"})
193
+ for utterance in utterances:
194
+ # Avisa já, antes de reconhecer (leva segundos): no
195
+ # modo manual o navegador fecha o microfone aqui.
196
+ await ws.send_json({"type": "utterance_end"})
197
+ await recognize_and_send(utterance)
198
+ elif msg.get("text"):
199
+ kind = json.loads(msg["text"]).get("type")
200
+ if kind == "flush":
201
+ pending = segmenter.flush()
202
+ segmenter.reset()
203
+ if pending is not None:
204
+ await recognize_and_send(pending)
205
+ elif kind == "reset":
206
+ segmenter.reset()
207
+ except WebSocketDisconnect:
208
+ pass
209
+
210
+ return app
poly_server/asr.py ADDED
@@ -0,0 +1,76 @@
1
+ """Reconhecimento de fala: idioma + transcrição."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from dataclasses import asdict, dataclass
8
+ from pathlib import Path
9
+ from typing import Protocol
10
+
11
+ import numpy as np
12
+
13
+
14
+ @dataclass
15
+ class Recognition:
16
+ language: str
17
+ confidence: float
18
+ text: str
19
+ latency_sec: float
20
+
21
+ def to_event(self) -> dict:
22
+ return {"type": "asr", **asdict(self)}
23
+
24
+
25
+ class Recognizer(Protocol):
26
+ def recognize(self, audio: np.ndarray) -> Recognition: ...
27
+
28
+
29
+ class WhisperRecognizer:
30
+ """faster-whisper. O modelo é carregado na primeira fala (ou em `load()`)."""
31
+
32
+ def __init__(
33
+ self,
34
+ model: str = "base",
35
+ *,
36
+ device: str = "auto",
37
+ compute_type: str = "int8",
38
+ download_root: Path | None = None,
39
+ ) -> None:
40
+ self._model_name = model
41
+ self._device = device
42
+ self._compute_type = compute_type
43
+ self._download_root = download_root
44
+ self._model = None
45
+ self._lock = threading.Lock()
46
+
47
+ def load(self):
48
+ with self._lock:
49
+ if self._model is None:
50
+ from faster_whisper import WhisperModel
51
+
52
+ self._model = WhisperModel(
53
+ self._model_name,
54
+ device=self._device,
55
+ compute_type=self._compute_type,
56
+ download_root=str(self._download_root) if self._download_root else None,
57
+ )
58
+ return self._model
59
+
60
+ def recognize(self, audio: np.ndarray) -> Recognition:
61
+ model = self.load()
62
+ t0 = time.time()
63
+ # Um modelo por vez: em CPU, rodar duas falas em paralelo só deixa as duas lentas.
64
+ with self._lock:
65
+ segments, info = model.transcribe(
66
+ audio,
67
+ beam_size=1,
68
+ condition_on_previous_text=False,
69
+ )
70
+ text = "".join(s.text for s in segments).strip()
71
+ return Recognition(
72
+ language=info.language,
73
+ confidence=round(float(info.language_probability), 4),
74
+ text=text,
75
+ latency_sec=round(time.time() - t0, 3),
76
+ )
poly_server/cli.py ADDED
@@ -0,0 +1,94 @@
1
+ """Linha de comando: poly-server serve | download | devices."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .config import Settings
11
+
12
+
13
+ def _serve(args: argparse.Namespace) -> None:
14
+ import uvicorn
15
+
16
+ from .app import create_app
17
+
18
+ settings = Settings.from_env(
19
+ host=args.host,
20
+ port=args.port,
21
+ whisper_model=args.model,
22
+ mic_device=args.mic_device,
23
+ cors_origins=args.cors.split(",") if args.cors else None,
24
+ mic=False if args.no_mic else None,
25
+ auto_download=False if args.offline else None,
26
+ )
27
+ uvicorn.run(create_app(settings), host=settings.host, port=settings.port)
28
+
29
+
30
+ def _download(args: argparse.Namespace) -> None:
31
+ """Prepara uma instalação offline: modelo de voz + pacotes de tradução."""
32
+ from .asr import WhisperRecognizer
33
+ from .translate import ArgosTranslator, UnsupportedLanguagePair
34
+
35
+ settings = Settings.from_env(whisper_model=args.model)
36
+
37
+ print(f"Downloading speech model '{settings.whisper_model}'...")
38
+ WhisperRecognizer(settings.whisper_model, download_root=settings.cache_dir / "whisper").load()
39
+
40
+ translator = ArgosTranslator(auto_download=True)
41
+ targets = [t.strip() for t in args.languages.split(",") if t.strip()]
42
+ failed = []
43
+ for target in targets:
44
+ print(f"Translation {args.base} -> {target}...")
45
+ try:
46
+ translator.ensure_pair(args.base, target)
47
+ except UnsupportedLanguagePair:
48
+ failed.append(target)
49
+ if failed:
50
+ print(f"No translation package available for: {', '.join(failed)}", file=sys.stderr)
51
+ sys.exit(1)
52
+ print("Done.")
53
+
54
+
55
+ def _devices(_: argparse.Namespace) -> None:
56
+ from .mic import list_input_devices
57
+
58
+ for d in list_input_devices():
59
+ print(f"{d['index']:>3} {d['name']} ({d['channels']} ch)")
60
+
61
+
62
+ def main(argv: list[str] | None = None) -> None:
63
+ parser = argparse.ArgumentParser(prog="poly-server", description="Speech language detection + UI translation server for Poly.")
64
+ parser.add_argument("--version", action="version", version=__version__)
65
+ sub = parser.add_subparsers(dest="command", required=True)
66
+
67
+ serve = sub.add_parser("serve", help="start the server")
68
+ serve.add_argument("--host")
69
+ serve.add_argument("--port", type=int)
70
+ serve.add_argument("--model", help="whisper model: tiny, base, small, medium, large-v3")
71
+ serve.add_argument("--mic-device", help="input device index or name (see `poly-server devices`)")
72
+ serve.add_argument("--no-mic", action="store_true", help="don't capture the local microphone (browser audio only)")
73
+ serve.add_argument("--cors", help="comma-separated allowed origins (default: *)")
74
+ serve.add_argument("--offline", action="store_true", help="never download translation packages")
75
+ serve.set_defaults(func=_serve)
76
+
77
+ download = sub.add_parser("download", help="download models for offline use")
78
+ download.add_argument("--base", default="en", help="language your UI is written in (default: en)")
79
+ download.add_argument("--languages", required=True, help="comma-separated target languages, e.g. pt,es,fr,ar")
80
+ download.add_argument("--model", help="whisper model to download")
81
+ download.set_defaults(func=_download)
82
+
83
+ devices = sub.add_parser("devices", help="list microphones")
84
+ devices.set_defaults(func=_devices)
85
+
86
+ args = parser.parse_args(argv)
87
+ if getattr(args, "mic_device", None) and str(args.mic_device).isdigit():
88
+ args.mic_device = int(args.mic_device)
89
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
90
+ args.func(args)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
poly_server/config.py ADDED
@@ -0,0 +1,71 @@
1
+ """Configuração do servidor, lida de variáveis de ambiente POLY_*."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field, fields
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ def _default_cache_dir() -> Path:
12
+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
13
+ return Path(base) / "poly-server"
14
+
15
+
16
+ @dataclass
17
+ class Settings:
18
+ host: str = "127.0.0.1"
19
+ port: int = 8000
20
+ # Origens liberadas no CORS. "*" libera qualquer uma.
21
+ cors_origins: list[str] = field(default_factory=lambda: ["*"])
22
+
23
+ # Captura o microfone do próprio computador (modo quiosque). Com False,
24
+ # o áudio só chega pelo navegador, via WebSocket /ws/audio.
25
+ mic: bool = True
26
+ # Índice ou nome do dispositivo de entrada (veja `poly-server devices`).
27
+ mic_device: int | str | None = None
28
+
29
+ # Modelo do faster-whisper: tiny, base, small, medium, large-v3...
30
+ whisper_model: str = "base"
31
+ whisper_device: str = "auto" # auto, cpu, cuda
32
+ whisper_compute_type: str = "int8"
33
+
34
+ # Segmentação da fala
35
+ vad_mode: int = 2 # 0 = menos agressivo, 3 = mais agressivo
36
+ frame_ms: int = 30 # webrtcvad aceita 10, 20 ou 30
37
+ pre_roll_ms: int = 200
38
+ start_trigger_ms: int = 150
39
+ end_trigger_ms: int = 600
40
+ max_utterance_sec: float = 12.0
41
+
42
+ cache_dir: Path = field(default_factory=_default_cache_dir)
43
+ # Baixa pacotes de tradução sob demanda. Em quiosque offline, deixe False
44
+ # e use `poly-server download` na instalação.
45
+ auto_download: bool = True
46
+
47
+ @classmethod
48
+ def from_env(cls, **overrides: Any) -> "Settings":
49
+ values: dict[str, Any] = {}
50
+ for f in fields(cls):
51
+ raw = os.environ.get(f"POLY_{f.name.upper()}")
52
+ if raw is not None:
53
+ values[f.name] = _parse(f.name, raw)
54
+ values.update({k: v for k, v in overrides.items() if v is not None})
55
+ return cls(**values)
56
+
57
+
58
+ def _parse(name: str, raw: str) -> Any:
59
+ if name in {"port", "vad_mode", "frame_ms", "pre_roll_ms", "start_trigger_ms", "end_trigger_ms"}:
60
+ return int(raw)
61
+ if name == "max_utterance_sec":
62
+ return float(raw)
63
+ if name in {"mic", "auto_download"}:
64
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
65
+ if name == "cors_origins":
66
+ return [o.strip() for o in raw.split(",") if o.strip()]
67
+ if name == "cache_dir":
68
+ return Path(raw).expanduser()
69
+ if name == "mic_device":
70
+ return int(raw) if raw.isdigit() else raw
71
+ return raw
poly_server/events.py ADDED
@@ -0,0 +1,39 @@
1
+ """Distribui eventos de reconhecimento para todos os clientes conectados."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+
8
+ class EventHub:
9
+ """
10
+ Cada cliente do WebSocket /ws recebe todos os eventos. (Na versão anterior
11
+ havia uma fila única, e com duas abas abertas cada evento ia só para uma.)
12
+ """
13
+
14
+ def __init__(self) -> None:
15
+ self._subscribers: set[asyncio.Queue[dict]] = set()
16
+ self._loop: asyncio.AbstractEventLoop | None = None
17
+
18
+ def bind(self, loop: asyncio.AbstractEventLoop) -> None:
19
+ self._loop = loop
20
+
21
+ def subscribe(self) -> asyncio.Queue[dict]:
22
+ q: asyncio.Queue[dict] = asyncio.Queue(maxsize=100)
23
+ self._subscribers.add(q)
24
+ return q
25
+
26
+ def unsubscribe(self, q: asyncio.Queue[dict]) -> None:
27
+ self._subscribers.discard(q)
28
+
29
+ def _deliver(self, event: dict) -> None:
30
+ for q in list(self._subscribers):
31
+ if q.full():
32
+ q.get_nowait() # cliente lento: descarta o evento mais antigo
33
+ q.put_nowait(event)
34
+
35
+ def publish(self, event: dict) -> None:
36
+ """Pode ser chamado de qualquer thread."""
37
+ if self._loop is None:
38
+ return
39
+ self._loop.call_soon_threadsafe(self._deliver, event)
@@ -0,0 +1,104 @@
1
+ """Controle de escuta do microfone local: contínua ou sob demanda (botão)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ from typing import Callable
8
+
9
+ import numpy as np
10
+
11
+ from .asr import Recognition
12
+ from .vad import Segmenter
13
+
14
+ log = logging.getLogger("poly_server")
15
+
16
+
17
+ class ListeningController:
18
+ """
19
+ Recebe o áudio do microfone local e decide o que vai para o
20
+ reconhecimento.
21
+
22
+ - Modo contínuo (padrão): toda fala detectada é reconhecida.
23
+ - Modo manual: enquanto algum cliente pedir `listening: "manual"`, o áudio
24
+ só é processado entre `start()` e o fim da fala (silêncio) ou `stop()`.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ segmenter: Segmenter,
30
+ recognize: Callable[[np.ndarray], Recognition],
31
+ publish: Callable[[dict], None],
32
+ ) -> None:
33
+ self._segmenter = segmenter
34
+ self._recognize = recognize
35
+ self._publish = publish
36
+ self._lock = threading.Lock()
37
+ self._manual_clients = 0
38
+ self._listening = False
39
+
40
+ @property
41
+ def manual(self) -> bool:
42
+ return self._manual_clients > 0
43
+
44
+ @property
45
+ def listening(self) -> bool:
46
+ return self._listening
47
+
48
+ def add_manual_client(self) -> None:
49
+ with self._lock:
50
+ self._manual_clients += 1
51
+ self._reset()
52
+
53
+ def remove_manual_client(self) -> None:
54
+ with self._lock:
55
+ self._manual_clients = max(0, self._manual_clients - 1)
56
+ if self._manual_clients == 0:
57
+ self._listening = False
58
+
59
+ def start(self) -> None:
60
+ with self._lock:
61
+ self._reset()
62
+ self._listening = True
63
+ self._publish({"type": "listening", "listening": True})
64
+
65
+ def stop(self) -> None:
66
+ """Para de escutar e reconhece o que já foi dito, se houver."""
67
+ with self._lock:
68
+ was_listening = self._listening
69
+ self._listening = False
70
+ pending = self._segmenter.flush()
71
+ self._reset()
72
+ if pending is not None:
73
+ self._emit(pending)
74
+ if was_listening:
75
+ self._publish({"type": "listening", "listening": False})
76
+
77
+ def feed(self, block: np.ndarray) -> None:
78
+ """Chamado pela thread do microfone."""
79
+ with self._lock:
80
+ if self.manual and not self._listening:
81
+ return
82
+ was_speaking = self._segmenter.in_speech
83
+ utterances = self._segmenter.feed(block)
84
+ started = not was_speaking and (self._segmenter.in_speech or bool(utterances))
85
+ ended = bool(utterances) and self.manual
86
+ if ended:
87
+ # Fim da fala (silêncio): a escuta manual termina aqui.
88
+ self._listening = False
89
+ self._reset()
90
+ if started:
91
+ self._publish({"type": "speech_start"})
92
+ for u in utterances:
93
+ self._emit(u)
94
+ if ended:
95
+ self._publish({"type": "listening", "listening": False})
96
+
97
+ def _emit(self, audio: np.ndarray) -> None:
98
+ try:
99
+ self._publish(self._recognize(audio).to_event())
100
+ except Exception:
101
+ log.exception("recognition failed")
102
+
103
+ def _reset(self) -> None:
104
+ self._segmenter.reset()
poly_server/mic.py ADDED
@@ -0,0 +1,78 @@
1
+ """Captura do microfone local (modo quiosque)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import queue
7
+ import threading
8
+ from typing import Callable
9
+
10
+ import numpy as np
11
+
12
+ from .vad import SAMPLE_RATE
13
+
14
+ log = logging.getLogger("poly_server")
15
+
16
+
17
+ def _sounddevice():
18
+ try:
19
+ import sounddevice
20
+ except (ImportError, OSError) as e: # OSError: PortAudio ausente no sistema
21
+ raise RuntimeError(
22
+ "Local microphone capture needs sounddevice + PortAudio: "
23
+ "pip install 'poly-server[mic]' (and libportaudio2 on Linux)."
24
+ ) from e
25
+ return sounddevice
26
+
27
+
28
+ def list_input_devices() -> list[dict]:
29
+ sd = _sounddevice()
30
+ return [
31
+ {"index": i, "name": d["name"], "channels": d["max_input_channels"]}
32
+ for i, d in enumerate(sd.query_devices())
33
+ if d["max_input_channels"] > 0
34
+ ]
35
+
36
+
37
+ class MicSource:
38
+ """Lê o microfone numa thread e entrega blocos float32 mono 16 kHz."""
39
+
40
+ def __init__(self, on_audio: Callable[[np.ndarray], None], device: int | str | None = None) -> None:
41
+ self._on_audio = on_audio
42
+ self._device = device
43
+ self._queue: queue.Queue[np.ndarray] = queue.Queue()
44
+ self._stop = threading.Event()
45
+ self._thread: threading.Thread | None = None
46
+
47
+ def start(self) -> None:
48
+ sd = _sounddevice()
49
+
50
+ def callback(indata, frames, time_info, status):
51
+ if status:
52
+ log.warning("mic: %s", status)
53
+ self._queue.put(indata[:, 0].copy())
54
+
55
+ def run():
56
+ try:
57
+ with sd.InputStream(
58
+ samplerate=SAMPLE_RATE,
59
+ channels=1,
60
+ dtype="float32",
61
+ callback=callback,
62
+ device=self._device,
63
+ ):
64
+ log.info("mic: capturing from %s", self._device if self._device is not None else "default device")
65
+ while not self._stop.is_set():
66
+ try:
67
+ block = self._queue.get(timeout=0.5)
68
+ except queue.Empty:
69
+ continue
70
+ self._on_audio(block)
71
+ except Exception:
72
+ log.exception("mic: capture stopped")
73
+
74
+ self._thread = threading.Thread(target=run, name="poly-mic", daemon=True)
75
+ self._thread.start()
76
+
77
+ def stop(self) -> None:
78
+ self._stop.set()
@@ -0,0 +1,151 @@
1
+ """Tradução de textos: Argos Translate (offline) + cache em disco."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sqlite3
7
+ import threading
8
+ from pathlib import Path
9
+ from typing import Protocol
10
+
11
+ log = logging.getLogger("poly_server")
12
+
13
+
14
+ class UnsupportedLanguagePair(Exception):
15
+ def __init__(self, source: str, target: str) -> None:
16
+ super().__init__(f"no translation available for {source} -> {target}")
17
+ self.source = source
18
+ self.target = target
19
+
20
+
21
+ class Translator(Protocol):
22
+ def translate_many(self, texts: list[str], source: str, target: str) -> list[str]: ...
23
+
24
+
25
+ def normalize_lang(code: str | None) -> str:
26
+ if not code:
27
+ return "en"
28
+ return str(code).strip().lower().replace("_", "-").split("-")[0]
29
+
30
+
31
+ class ArgosTranslator:
32
+ """
33
+ Usa os pacotes do Argos instalados e, se `auto_download`, baixa os que
34
+ faltarem. Quando não existe pacote direto (ex.: pt -> ja), traduz passando
35
+ pelo idioma `pivot` (inglês), que é como a maioria dos pacotes do Argos é
36
+ publicada.
37
+ """
38
+
39
+ def __init__(self, *, auto_download: bool = True, pivot: str = "en") -> None:
40
+ self.auto_download = auto_download
41
+ self.pivot = pivot
42
+ self._ready: set[tuple[str, str]] = set()
43
+ self._lock = threading.Lock()
44
+ self._index_updated = False
45
+
46
+ def _installed_pairs(self) -> set[tuple[str, str]]:
47
+ from argostranslate import package
48
+
49
+ return {(p.from_code, p.to_code) for p in package.get_installed_packages()}
50
+
51
+ def _install(self, source: str, target: str) -> bool:
52
+ from argostranslate import package
53
+
54
+ if not self.auto_download:
55
+ return False
56
+ if not self._index_updated:
57
+ package.update_package_index()
58
+ self._index_updated = True
59
+ pkg = next(
60
+ (p for p in package.get_available_packages() if p.from_code == source and p.to_code == target),
61
+ None,
62
+ )
63
+ if pkg is None:
64
+ return False
65
+ log.info("Argos: installing %s -> %s", source, target)
66
+ package.install_from_path(pkg.download())
67
+ return True
68
+
69
+ def _ensure_direct(self, source: str, target: str) -> bool:
70
+ if (source, target) in self._installed_pairs():
71
+ return True
72
+ return self._install(source, target)
73
+
74
+ def ensure_pair(self, source: str, target: str) -> None:
75
+ if source == target or (source, target) in self._ready:
76
+ return
77
+ with self._lock:
78
+ if (source, target) in self._ready:
79
+ return
80
+ ok = self._ensure_direct(source, target)
81
+ if not ok and self.pivot not in (source, target):
82
+ ok = self._ensure_direct(source, self.pivot) and self._ensure_direct(self.pivot, target)
83
+ if not ok:
84
+ raise UnsupportedLanguagePair(source, target)
85
+ self._ready.add((source, target))
86
+
87
+ def _translate_one(self, text: str, source: str, target: str) -> str:
88
+ from argostranslate import translate
89
+
90
+ if (source, target) in self._installed_pairs():
91
+ return translate.translate(text, source, target)
92
+ middle = translate.translate(text, source, self.pivot)
93
+ return translate.translate(middle, self.pivot, target)
94
+
95
+ def translate_many(self, texts: list[str], source: str, target: str) -> list[str]:
96
+ source, target = normalize_lang(source), normalize_lang(target)
97
+ if source == target:
98
+ return list(texts)
99
+ self.ensure_pair(source, target)
100
+ memo: dict[str, str] = {}
101
+ out = []
102
+ for t in texts:
103
+ if t not in memo:
104
+ memo[t] = self._translate_one(t, source, target) if t.strip() else t
105
+ out.append(memo[t])
106
+ return out
107
+
108
+
109
+ class CachedTranslator:
110
+ """Guarda as traduções em SQLite: o mesmo texto não é traduzido duas vezes."""
111
+
112
+ def __init__(self, inner: Translator, path: Path) -> None:
113
+ self.inner = inner
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ self._db = sqlite3.connect(path, check_same_thread=False)
116
+ self._db.execute(
117
+ "CREATE TABLE IF NOT EXISTS translations ("
118
+ " source TEXT, target TEXT, text TEXT, translation TEXT,"
119
+ " PRIMARY KEY (source, target, text))"
120
+ )
121
+ self._db.commit()
122
+ self._lock = threading.Lock()
123
+
124
+ def translate_many(self, texts: list[str], source: str, target: str) -> list[str]:
125
+ source, target = normalize_lang(source), normalize_lang(target)
126
+ found: dict[str, str] = {}
127
+ unique = list(dict.fromkeys(texts))
128
+
129
+ with self._lock:
130
+ for i in range(0, len(unique), 500):
131
+ chunk = unique[i : i + 500]
132
+ rows = self._db.execute(
133
+ "SELECT text, translation FROM translations WHERE source = ? AND target = ?"
134
+ f" AND text IN ({','.join('?' * len(chunk))})",
135
+ [source, target, *chunk],
136
+ ).fetchall()
137
+ found.update(rows)
138
+
139
+ missing = [t for t in unique if t not in found]
140
+ if missing:
141
+ translated = self.inner.translate_many(missing, source, target)
142
+ new = dict(zip(missing, translated))
143
+ found.update(new)
144
+ with self._lock:
145
+ self._db.executemany(
146
+ "INSERT OR REPLACE INTO translations VALUES (?, ?, ?, ?)",
147
+ [(source, target, k, v) for k, v in new.items()],
148
+ )
149
+ self._db.commit()
150
+
151
+ return [found[t] for t in texts]
poly_server/vad.py ADDED
@@ -0,0 +1,110 @@
1
+ """Separa o áudio contínuo em falas (utterances) usando detecção de voz."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ from typing import Callable
7
+
8
+ import numpy as np
9
+
10
+ SAMPLE_RATE = 16000
11
+
12
+ IsSpeech = Callable[[bytes, int], bool]
13
+
14
+
15
+ def float32_to_pcm16(x: np.ndarray) -> bytes:
16
+ return (np.clip(x, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()
17
+
18
+
19
+ def pcm16_to_float32(data: bytes) -> np.ndarray:
20
+ return np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
21
+
22
+
23
+ class Segmenter:
24
+ """
25
+ Recebe áudio mono 16 kHz em blocos de qualquer tamanho e devolve as falas
26
+ completas: começa quando há voz por `start_trigger_ms`, termina após
27
+ `end_trigger_ms` de silêncio ou ao atingir `max_utterance_sec`.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ vad_mode: int = 2,
34
+ frame_ms: int = 30,
35
+ pre_roll_ms: int = 200,
36
+ start_trigger_ms: int = 150,
37
+ end_trigger_ms: int = 600,
38
+ max_utterance_sec: float = 12.0,
39
+ is_speech: IsSpeech | None = None,
40
+ ) -> None:
41
+ if is_speech is None:
42
+ import webrtcvad
43
+
44
+ is_speech = webrtcvad.Vad(vad_mode).is_speech
45
+ self._is_speech = is_speech
46
+
47
+ self.frame_len = int(SAMPLE_RATE * frame_ms / 1000)
48
+ self._start_frames = max(1, start_trigger_ms // frame_ms)
49
+ self._end_frames = max(1, end_trigger_ms // frame_ms)
50
+ self._max_frames = int(max_utterance_sec * 1000 / frame_ms)
51
+
52
+ self._ring: collections.deque[np.ndarray] = collections.deque(
53
+ maxlen=max(0, pre_roll_ms // frame_ms)
54
+ )
55
+ self._voiced: list[np.ndarray] = []
56
+ self._in_speech = False
57
+ self._speech_run = 0
58
+ self._silence_run = 0
59
+ self._buffer = np.zeros((0,), dtype=np.float32)
60
+
61
+ def feed(self, samples: np.ndarray) -> list[np.ndarray]:
62
+ self._buffer = np.concatenate([self._buffer, samples.astype(np.float32, copy=False)])
63
+ done: list[np.ndarray] = []
64
+
65
+ while len(self._buffer) >= self.frame_len:
66
+ frame = self._buffer[: self.frame_len]
67
+ self._buffer = self._buffer[self.frame_len :]
68
+ speech = self._is_speech(float32_to_pcm16(frame), SAMPLE_RATE)
69
+
70
+ if not self._in_speech:
71
+ self._ring.append(frame)
72
+ self._speech_run = self._speech_run + 1 if speech else 0
73
+ if self._speech_run >= self._start_frames:
74
+ self._in_speech = True
75
+ self._voiced = list(self._ring)
76
+ self._ring.clear()
77
+ self._speech_run = 0
78
+ self._silence_run = 0
79
+ else:
80
+ self._voiced.append(frame)
81
+ self._silence_run = 0 if speech else self._silence_run + 1
82
+ if self._silence_run >= self._end_frames or len(self._voiced) >= self._max_frames:
83
+ done.append(np.concatenate(self._voiced))
84
+ self._voiced = []
85
+ self._in_speech = False
86
+ self._silence_run = 0
87
+
88
+ return done
89
+
90
+ @property
91
+ def in_speech(self) -> bool:
92
+ return self._in_speech
93
+
94
+ def reset(self) -> None:
95
+ """Descarta tudo o que estava em andamento."""
96
+ self._ring.clear()
97
+ self._voiced = []
98
+ self._in_speech = False
99
+ self._speech_run = 0
100
+ self._silence_run = 0
101
+ self._buffer = np.zeros((0,), dtype=np.float32)
102
+
103
+ def flush(self) -> np.ndarray | None:
104
+ """Entrega a fala em andamento, se houver (ex.: ao fechar a conexão)."""
105
+ if not self._in_speech or not self._voiced:
106
+ return None
107
+ out = np.concatenate(self._voiced)
108
+ self._voiced = []
109
+ self._in_speech = False
110
+ return out
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: poly-server
3
+ Version: 0.1.0
4
+ Summary: Speech language detection and offline UI translation server for Poly voice-driven interfaces.
5
+ Project-URL: Homepage, https://github.com/VictorAGuerra/Poly-SLID-Interface-Translator
6
+ Project-URL: Repository, https://github.com/VictorAGuerra/Poly-SLID-Interface-Translator
7
+ Project-URL: Issues, https://github.com/VictorAGuerra/Poly-SLID-Interface-Translator/issues
8
+ Author: Victor A. Guerra
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: accessibility,i18n,kiosk,language-detection,self-service,speech,translation,whisper
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
17
+ Classifier: Topic :: Software Development :: Internationalization
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: argostranslate>=1.9
20
+ Requires-Dist: fastapi>=0.115
21
+ Requires-Dist: faster-whisper>=1.1
22
+ Requires-Dist: numpy>=1.24
23
+ Requires-Dist: uvicorn[standard]>=0.30
24
+ Requires-Dist: webrtcvad-wheels>=2.0.14
25
+ Provides-Extra: dev
26
+ Requires-Dist: httpx>=0.27; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Provides-Extra: mic
29
+ Requires-Dist: sounddevice>=0.5; extra == 'mic'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # poly-server
33
+
34
+ **English** · [Português](#português)
35
+
36
+ Speech language detection and offline UI translation server for
37
+ [Poly](https://www.npmjs.com/package/@swalay/poly-react), voice-driven
38
+ interfaces for self-service kiosks.
39
+
40
+ - **Speech → language** with [faster-whisper](https://github.com/SYSTRAN/faster-whisper).
41
+ - **UI translation** with [Argos Translate](https://github.com/argosopentech/argos-translate),
42
+ fully offline, with an English pivot when there's no direct language pair
43
+ and a persistent SQLite cache.
44
+ - **Two audio modes:** the server's own microphone (kiosk: screen and server on
45
+ the same machine) or audio streamed from the browser.
46
+ - Nothing leaves the device: no cloud APIs.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ # CPU-only PyTorch first (Argos needs it); avoids ~3 GB of CUDA libraries
52
+ pip install torch --index-url https://download.pytorch.org/whl/cpu
53
+ pip install "poly-server[mic]"
54
+ ```
55
+
56
+ The `mic` extra enables local microphone capture (needs PortAudio:
57
+ `sudo apt install libportaudio2` on Debian/Ubuntu). Skip it if audio only
58
+ comes from the browser.
59
+
60
+ ## Run
61
+
62
+ ```bash
63
+ poly-server serve # http://127.0.0.1:8000, local microphone
64
+ poly-server serve --no-mic # browser audio only
65
+ poly-server devices # list microphones
66
+ poly-server serve --mic-device 2
67
+ ```
68
+
69
+ ### Offline kiosks
70
+
71
+ Download everything once during installation, then run without network:
72
+
73
+ ```bash
74
+ poly-server download --base en --languages pt,es,fr,ar,ja,zh
75
+ poly-server serve --offline
76
+ ```
77
+
78
+ ## Configuration
79
+
80
+ Every option can be set with a `POLY_*` environment variable:
81
+
82
+ | Variable | Default | |
83
+ | --- | --- | --- |
84
+ | `POLY_HOST` / `POLY_PORT` | `127.0.0.1` / `8000` | |
85
+ | `POLY_CORS_ORIGINS` | `*` | Comma-separated allowed origins. |
86
+ | `POLY_MIC` | `true` | Capture the local microphone. |
87
+ | `POLY_MIC_DEVICE` | system default | Input device index or name. |
88
+ | `POLY_WHISPER_MODEL` | `base` | `tiny`, `base`, `small`, `medium`, `large-v3`. |
89
+ | `POLY_WHISPER_DEVICE` | `auto` | `cpu`, `cuda`, `auto`. |
90
+ | `POLY_WHISPER_COMPUTE_TYPE` | `int8` | |
91
+ | `POLY_VAD_MODE` | `2` | 0 (lenient) to 3 (aggressive) voice detection. |
92
+ | `POLY_END_TRIGGER_MS` | `600` | Silence that ends an utterance. |
93
+ | `POLY_MAX_UTTERANCE_SEC` | `12` | |
94
+ | `POLY_CACHE_DIR` | `~/.cache/poly-server` | Models and translation cache. |
95
+ | `POLY_AUTO_DOWNLOAD` | `true` | Download translation packages on demand. |
96
+
97
+ ## API
98
+
99
+ | Endpoint | |
100
+ | --- | --- |
101
+ | `GET /health` | `{ ok, version, mic }` |
102
+ | `POST /i18n/auto-translate` | `{ source_lang, target_lang, texts: { key: text } }` → `{ target_lang, texts }`. Returns `422` with `code: "unsupported_language_pair"` when no translation exists. |
103
+ | `WS /ws` | Recognition events from the local microphone, broadcast to every client. Send `{"type":"config","listening":"manual"}` to listen only on demand, then `{"type":"listen","action":"start"\|"stop"}`; the server replies with `{"type":"listening","listening":bool}` and `{"type":"speech_start"}`. |
104
+ | `WS /ws/audio` | Send binary PCM16 LE mono 16 kHz; receive `{"type":"speech_start"}` / `{"type":"utterance_end"}` as speech starts and ends, then the recognition event. Text messages: `{"type":"flush"}` recognizes the speech in progress, `{"type":"reset"}` discards it. |
105
+
106
+ Event: `{ "type": "asr", "language": "pt", "confidence": 0.97, "text": "...", "latency_sec": 1.4 }`
107
+
108
+ ### Embedding
109
+
110
+ ```python
111
+ from poly_server import Settings, create_app
112
+
113
+ app = create_app(Settings(mic=False, whisper_model="small"))
114
+ ```
115
+
116
+ `create_app` also accepts custom `recognizer` and `translator` objects, to plug
117
+ in another speech model or translation service.
118
+
119
+ ## License
120
+
121
+ MIT
122
+
123
+ ---
124
+
125
+ ## Português
126
+
127
+ Servidor de detecção do idioma falado e tradução offline de interfaces para o
128
+ Poly.
129
+
130
+ - **Fala → idioma** com faster-whisper.
131
+ - **Tradução** com Argos Translate, 100% offline, passando pelo inglês quando
132
+ não há pacote direto entre dois idiomas, e com cache em disco (SQLite).
133
+ - **Dois modos de áudio:** o microfone do próprio servidor (quiosque) ou o
134
+ áudio enviado pelo navegador.
135
+ - Nada sai do aparelho: nenhuma API na nuvem.
136
+
137
+ Instalação, execução e configuração: veja os comandos acima. Para quiosques
138
+ sem internet, rode `poly-server download` na instalação e depois
139
+ `poly-server serve --offline`.
@@ -0,0 +1,16 @@
1
+ poly_server/__init__.py,sha256=nWgA07lcHtwMmj54YvbOeYvk-vuiV78StlbrDoSYLUw,221
2
+ poly_server/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
3
+ poly_server/app.py,sha256=LIvgchzoHbuX3T4X74Q9y3ysIc9yHR9oz3eZBYOTjO8,7838
4
+ poly_server/asr.py,sha256=xSC4rBRe6MQZ337Y8eHBz_5EeK-tfcf1YHN3v6W8aA8,2161
5
+ poly_server/cli.py,sha256=w8NMie1Rx93SFPjGMumwiLYCyxtY3vG6nAIIumV-V_s,3707
6
+ poly_server/config.py,sha256=75J9cFeWhNQCwTXA61nDUFitNqdLjbCS5XZff560IFQ,2525
7
+ poly_server/events.py,sha256=QKF8T7_M6AOkEK6DSUMMPzPqHxz_M62In7a2UV0kgS8,1253
8
+ poly_server/listening.py,sha256=8A8KdIT78PIa45WRUXOsE-r1EBItNGw2zaAe9Jnukbw,3254
9
+ poly_server/mic.py,sha256=1rbWK-DmMcEaEnBhupS_zZJaMyCEocVydrLP27V2E-g,2434
10
+ poly_server/translate.py,sha256=sBgx3JKq-nXrXG4e7LJDnrrQft1BkNLSlBLLS6y6T7I,5601
11
+ poly_server/vad.py,sha256=g1_K4I6WOgAO6ji1CzopwBuYlgAhwLIIyTnCWs-QmlM,3771
12
+ poly_server-0.1.0.dist-info/METADATA,sha256=FqHlEWsBpxVO7egosxK9-D8BeSqcbUAI--0YbJcuz2o,5624
13
+ poly_server-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ poly_server-0.1.0.dist-info/entry_points.txt,sha256=wFdQLFXPm1Z4qsUoCzuTPRLDTjrDl1L17V-0COHzztI,53
15
+ poly_server-0.1.0.dist-info/licenses/LICENSE,sha256=PIxwkioaxYjQqUU2qSOoVZVDAiPcW9MZ2Kq9l_ec01o,1073
16
+ poly_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ poly-server = poly_server.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Victor A. Guerra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.