mina-voice-assistant 0.1.0.dev11__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.
- mina/__init__.py +6 -0
- mina/cli.py +37 -0
- mina/core.py +9 -0
- mina/ports.py +11 -0
- mina/protocol.py +60 -0
- mina/service.py +86 -0
- mina_voice_assistant-0.1.0.dev11.dist-info/METADATA +6 -0
- mina_voice_assistant-0.1.0.dev11.dist-info/RECORD +11 -0
- mina_voice_assistant-0.1.0.dev11.dist-info/WHEEL +5 -0
- mina_voice_assistant-0.1.0.dev11.dist-info/entry_points.txt +3 -0
- mina_voice_assistant-0.1.0.dev11.dist-info/top_level.txt +1 -0
mina/__init__.py
ADDED
mina/cli.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import socket
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from mina.protocol import MAX_MESSAGE_BYTES, decode_response, encode_request
|
|
7
|
+
from mina.service import DEFAULT_SOCKET_PATH
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def send_text(text: str, socket_path: Path = DEFAULT_SOCKET_PATH) -> str:
|
|
11
|
+
if not hasattr(socket, "AF_UNIX"):
|
|
12
|
+
raise RuntimeError("Unix domain sockets are not supported on this platform")
|
|
13
|
+
|
|
14
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
|
15
|
+
connection.connect(str(socket_path))
|
|
16
|
+
connection.sendall(encode_request(text))
|
|
17
|
+
with connection.makefile("rb") as response_stream:
|
|
18
|
+
response = response_stream.readline(MAX_MESSAGE_BYTES + 1024)
|
|
19
|
+
if not response:
|
|
20
|
+
raise RuntimeError("Mina service closed the connection without a response")
|
|
21
|
+
return decode_response(response)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main() -> int:
|
|
25
|
+
parser = argparse.ArgumentParser(prog="mina")
|
|
26
|
+
parser.add_argument("text", help="Text request to send to Mina")
|
|
27
|
+
parser.add_argument("--socket-path", type=Path, default=DEFAULT_SOCKET_PATH)
|
|
28
|
+
arguments = parser.parse_args()
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
response = send_text(arguments.text, arguments.socket_path)
|
|
32
|
+
except (OSError, RuntimeError, ValueError) as error:
|
|
33
|
+
print(f"mina: {error}", file=sys.stderr)
|
|
34
|
+
return 1
|
|
35
|
+
|
|
36
|
+
print(response)
|
|
37
|
+
return 0
|
mina/core.py
ADDED
mina/ports.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from typing import Protocol
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TextInputPort(Protocol):
|
|
5
|
+
def submit(self, request: str) -> None:
|
|
6
|
+
"""Submit a text request to the core."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TextOutputPort(Protocol):
|
|
10
|
+
def send(self, response: str) -> None:
|
|
11
|
+
"""Deliver a text response from the core."""
|
mina/protocol.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from mina import Core
|
|
6
|
+
|
|
7
|
+
MAX_MESSAGE_BYTES = 65536
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class _Response:
|
|
12
|
+
def __init__(self) -> None:
|
|
13
|
+
self.value: Optional[str] = None
|
|
14
|
+
|
|
15
|
+
def send(self, response: str) -> None:
|
|
16
|
+
self.value = response
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def encode_request(text: str) -> bytes:
|
|
20
|
+
message = json.dumps({"text": text}, ensure_ascii=False).encode("utf-8") + b"\n"
|
|
21
|
+
if len(message) > MAX_MESSAGE_BYTES:
|
|
22
|
+
raise ValueError("Text request is too large")
|
|
23
|
+
return message
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def decode_response(message: bytes) -> str:
|
|
27
|
+
try:
|
|
28
|
+
response = json.loads(message.decode("utf-8"))
|
|
29
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
30
|
+
raise RuntimeError("Mina service returned an invalid response") from error
|
|
31
|
+
|
|
32
|
+
if not isinstance(response, dict):
|
|
33
|
+
raise RuntimeError("Mina service returned an invalid response")
|
|
34
|
+
if "error" in response:
|
|
35
|
+
raise RuntimeError(str(response["error"]))
|
|
36
|
+
result = response.get("response")
|
|
37
|
+
if not isinstance(result, str):
|
|
38
|
+
raise RuntimeError("Mina service returned an invalid response")
|
|
39
|
+
return result
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def process_request(message: bytes) -> bytes:
|
|
43
|
+
if len(message) > MAX_MESSAGE_BYTES or not message.endswith(b"\n"):
|
|
44
|
+
logger.warning("Rejected invalid text request")
|
|
45
|
+
return b'{"error":"Invalid request"}\n'
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
request = json.loads(message.decode("utf-8"))
|
|
49
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
50
|
+
logger.warning("Rejected invalid text request")
|
|
51
|
+
return b'{"error":"Invalid request"}\n'
|
|
52
|
+
|
|
53
|
+
if not isinstance(request, dict) or not isinstance(request.get("text"), str):
|
|
54
|
+
logger.warning("Rejected invalid text request")
|
|
55
|
+
return b'{"error":"Invalid request"}\n'
|
|
56
|
+
|
|
57
|
+
output = _Response()
|
|
58
|
+
Core(output).submit(request["text"])
|
|
59
|
+
logger.info("Processed text request")
|
|
60
|
+
return json.dumps({"response": output.value}, ensure_ascii=False).encode("utf-8") + b"\n"
|
mina/service.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import signal
|
|
5
|
+
import socket
|
|
6
|
+
import stat
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
from mina.protocol import MAX_MESSAGE_BYTES, process_request
|
|
12
|
+
|
|
13
|
+
DEFAULT_SOCKET_PATH = Path("/run/mina/mina.sock")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _remove_stale_socket(socket_path: Path) -> None:
|
|
17
|
+
if not socket_path.exists():
|
|
18
|
+
return
|
|
19
|
+
if not stat.S_ISSOCK(socket_path.stat().st_mode):
|
|
20
|
+
raise RuntimeError(f"Socket path exists and is not a socket: {socket_path}")
|
|
21
|
+
|
|
22
|
+
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
23
|
+
try:
|
|
24
|
+
probe.connect(str(socket_path))
|
|
25
|
+
except (ConnectionRefusedError, FileNotFoundError):
|
|
26
|
+
socket_path.unlink()
|
|
27
|
+
else:
|
|
28
|
+
raise RuntimeError(f"Mina service is already listening at {socket_path}")
|
|
29
|
+
finally:
|
|
30
|
+
probe.close()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def serve(
|
|
34
|
+
socket_path: Path = DEFAULT_SOCKET_PATH,
|
|
35
|
+
*,
|
|
36
|
+
stop_event: Optional[threading.Event] = None,
|
|
37
|
+
ready_event: Optional[threading.Event] = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
if not hasattr(socket, "AF_UNIX"):
|
|
40
|
+
raise RuntimeError("Unix domain sockets are not supported on this platform")
|
|
41
|
+
|
|
42
|
+
socket_path.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
_remove_stale_socket(socket_path)
|
|
44
|
+
|
|
45
|
+
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
46
|
+
listener.bind(str(socket_path))
|
|
47
|
+
os.chmod(socket_path, 0o660)
|
|
48
|
+
listener.listen()
|
|
49
|
+
listener.settimeout(0.2)
|
|
50
|
+
if ready_event is not None:
|
|
51
|
+
ready_event.set()
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
while stop_event is None or not stop_event.is_set():
|
|
55
|
+
try:
|
|
56
|
+
connection, _ = listener.accept()
|
|
57
|
+
except socket.timeout:
|
|
58
|
+
continue
|
|
59
|
+
with connection:
|
|
60
|
+
with connection.makefile("rb") as request_stream:
|
|
61
|
+
request = request_stream.readline(MAX_MESSAGE_BYTES + 1)
|
|
62
|
+
connection.sendall(process_request(request))
|
|
63
|
+
finally:
|
|
64
|
+
listener.close()
|
|
65
|
+
try:
|
|
66
|
+
socket_path.unlink()
|
|
67
|
+
except FileNotFoundError:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def main() -> int:
|
|
72
|
+
parser = argparse.ArgumentParser(prog="mina-service")
|
|
73
|
+
parser.add_argument("--socket-path", type=Path, default=DEFAULT_SOCKET_PATH)
|
|
74
|
+
arguments = parser.parse_args()
|
|
75
|
+
|
|
76
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
|
77
|
+
stop_event = threading.Event()
|
|
78
|
+
signal.signal(signal.SIGTERM, lambda *_: stop_event.set())
|
|
79
|
+
signal.signal(signal.SIGINT, lambda *_: stop_event.set())
|
|
80
|
+
try:
|
|
81
|
+
serve(arguments.socket_path, stop_event=stop_event)
|
|
82
|
+
except OSError as error:
|
|
83
|
+
parser.exit(1, f"mina-service: {error}\n")
|
|
84
|
+
except RuntimeError as error:
|
|
85
|
+
parser.exit(1, f"mina-service: {error}\n")
|
|
86
|
+
return 0
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
mina/__init__.py,sha256=OLS61bl9rpEaKiKxag4cYG9z5xgKLP7MqjMnoYzuf_c,171
|
|
2
|
+
mina/cli.py,sha256=ZKgPxT-odcEp15b4zUyNv3zLLiWJPnrnOn7lK7zh7E8,1325
|
|
3
|
+
mina/core.py,sha256=-ioX2kXJhi26u9YT4OTrWu3KWT72BES4D7ldBiLgvR8,263
|
|
4
|
+
mina/ports.py,sha256=9CbeW5Rrf3B_ZpoGE16DXl308fOM1kPXXviH2EX2ieU,284
|
|
5
|
+
mina/protocol.py,sha256=zPMZXz6oTaG4LgDFWhRlVpvVCVT2AFOph2BISFgkJig,1998
|
|
6
|
+
mina/service.py,sha256=w7vN3M6k8X6MpnjnB7bB06FpXsSiku20WCLx9uVjC4s,2722
|
|
7
|
+
mina_voice_assistant-0.1.0.dev11.dist-info/METADATA,sha256=IBL-HJ7aylCrx37jBznM-X5mNFnMr6xDUFITwAuTDxo,204
|
|
8
|
+
mina_voice_assistant-0.1.0.dev11.dist-info/WHEEL,sha256=16fc_9Rp854SLcdhaDEjr0u65p0e3FhZxihNgcnCE98,91
|
|
9
|
+
mina_voice_assistant-0.1.0.dev11.dist-info/entry_points.txt,sha256=k7bdg1OXf2UroLHlrniquIrNzkZ3RPOPxKb5hAfNuWo,72
|
|
10
|
+
mina_voice_assistant-0.1.0.dev11.dist-info/top_level.txt,sha256=oTcVH_arx9ngV8xvNwXtHzEJxpDdKla_CdlzNUGRuNI,5
|
|
11
|
+
mina_voice_assistant-0.1.0.dev11.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mina
|