seren-soma 1.0.0__tar.gz
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.
- seren_soma-1.0.0/PKG-INFO +50 -0
- seren_soma-1.0.0/README.md +30 -0
- seren_soma-1.0.0/pyproject.toml +50 -0
- seren_soma-1.0.0/seren-soma.yaml.sample +31 -0
- seren_soma-1.0.0/seren_soma/__init__.py +21 -0
- seren_soma-1.0.0/seren_soma/__main__.py +81 -0
- seren_soma-1.0.0/seren_soma/_describe.py +33 -0
- seren_soma-1.0.0/seren_soma/_diag.py +17 -0
- seren_soma-1.0.0/seren_soma/_version.py +24 -0
- seren_soma-1.0.0/seren_soma/config.py +190 -0
- seren_soma-1.0.0/seren_soma/touch_read.py +248 -0
- seren_soma-1.0.0/seren_soma/viewer/ui/body.html +23 -0
- seren_soma-1.0.0/seren_soma/viewer/ui/scripts.js +40 -0
- seren_soma-1.0.0/seren_soma/viewer/ui/styles.css +7 -0
- seren_soma-1.0.0/seren_soma/viewer/ui/tabs.html +2 -0
- seren_soma-1.0.0/seren_soma/voice.py +770 -0
- seren_soma-1.0.0/seren_soma.egg-info/PKG-INFO +50 -0
- seren_soma-1.0.0/seren_soma.egg-info/SOURCES.txt +25 -0
- seren_soma-1.0.0/seren_soma.egg-info/dependency_links.txt +1 -0
- seren_soma-1.0.0/seren_soma.egg-info/entry_points.txt +2 -0
- seren_soma-1.0.0/seren_soma.egg-info/requires.txt +8 -0
- seren_soma-1.0.0/seren_soma.egg-info/scm_file_list.json +20 -0
- seren_soma-1.0.0/seren_soma.egg-info/scm_version.json +8 -0
- seren_soma-1.0.0/seren_soma.egg-info/top_level.txt +1 -0
- seren_soma-1.0.0/setup.cfg +4 -0
- seren_soma-1.0.0/tests/test_package.py +127 -0
- seren_soma-1.0.0/tests/test_touch_read.py +200 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: seren-soma
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: The body's nervous system: a Stack-chan robot's voice, ears and touch, its faces' reactions, night mode and work hours.
|
|
5
|
+
Author: Chad Roesler
|
|
6
|
+
License-Expression: AGPL-3.0-or-later
|
|
7
|
+
Project-URL: Homepage, https://github.com/ChadRoesler/SerenSoma
|
|
8
|
+
Project-URL: Repository, https://github.com/ChadRoesler/SerenSoma
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/ChadRoesler/SerenSoma/issues
|
|
10
|
+
Keywords: seren,stackchan,robot,voice,xiaozhi,aiohttp
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: aiohttp>=3.9
|
|
14
|
+
Requires-Dist: av>=12
|
|
15
|
+
Requires-Dist: numpy>=1.24
|
|
16
|
+
Requires-Dist: pyyaml>=6.0
|
|
17
|
+
Requires-Dist: seren-meninges<7,>=6.0.0
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
20
|
+
|
|
21
|
+
# seren-soma
|
|
22
|
+
|
|
23
|
+
The nervous system of a [SerenSoma](https://github.com/ChadRoesler/SerenSoma) body: a Stack-chan
|
|
24
|
+
robot's voice, ears and touch.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install seren-soma
|
|
28
|
+
seren-soma # http://<this box>:7480/viewer
|
|
29
|
+
seren-soma --describe # one line of JSON, for installers
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- The robot checks in at `/ota/` and talks over a websocket. What it hears goes to Lodestar to be
|
|
33
|
+
transcribed and lands in `heard.jsonl`; what the mind says comes back through Lodestar, in its voice.
|
|
34
|
+
- It reads the head sensor into strokes, pokes, scritches and resting hands, and shows the face the
|
|
35
|
+
robot's face file names for each.
|
|
36
|
+
- It owns night mode (caps on the robot's lights, speaker and screen) and work hours, so the body
|
|
37
|
+
behaves with nothing else running.
|
|
38
|
+
|
|
39
|
+
Copy [`seren-soma.yaml.sample`](seren-soma.yaml.sample) to `~/seren-soma/seren-soma.yaml`.
|
|
40
|
+
Everything it keeps is in the state folder, `~/seren-soma/state/` by default: its two tokens, the
|
|
41
|
+
robot's control token, what was heard, the touch log, the settings and its own log.
|
|
42
|
+
|
|
43
|
+
**Its page** (`/viewer`) shows whether it's alive and its log. "Copy for help" replaces everything
|
|
44
|
+
that was heard with a word count, so the log can go to someone helping without what was said.
|
|
45
|
+
|
|
46
|
+
It binds the LAN, because the robot dials in, so it won't start without its API token; with none
|
|
47
|
+
configured it makes one in the state folder. The robot gets a separate token for its voice
|
|
48
|
+
connection, and the check-in answers only the robot's own address.
|
|
49
|
+
|
|
50
|
+
AGPL-3.0-or-later.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# seren-soma
|
|
2
|
+
|
|
3
|
+
The nervous system of a [SerenSoma](https://github.com/ChadRoesler/SerenSoma) body: a Stack-chan
|
|
4
|
+
robot's voice, ears and touch.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
pip install seren-soma
|
|
8
|
+
seren-soma # http://<this box>:7480/viewer
|
|
9
|
+
seren-soma --describe # one line of JSON, for installers
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
- The robot checks in at `/ota/` and talks over a websocket. What it hears goes to Lodestar to be
|
|
13
|
+
transcribed and lands in `heard.jsonl`; what the mind says comes back through Lodestar, in its voice.
|
|
14
|
+
- It reads the head sensor into strokes, pokes, scritches and resting hands, and shows the face the
|
|
15
|
+
robot's face file names for each.
|
|
16
|
+
- It owns night mode (caps on the robot's lights, speaker and screen) and work hours, so the body
|
|
17
|
+
behaves with nothing else running.
|
|
18
|
+
|
|
19
|
+
Copy [`seren-soma.yaml.sample`](seren-soma.yaml.sample) to `~/seren-soma/seren-soma.yaml`.
|
|
20
|
+
Everything it keeps is in the state folder, `~/seren-soma/state/` by default: its two tokens, the
|
|
21
|
+
robot's control token, what was heard, the touch log, the settings and its own log.
|
|
22
|
+
|
|
23
|
+
**Its page** (`/viewer`) shows whether it's alive and its log. "Copy for help" replaces everything
|
|
24
|
+
that was heard with a word count, so the log can go to someone helping without what was said.
|
|
25
|
+
|
|
26
|
+
It binds the LAN, because the robot dials in, so it won't start without its API token; with none
|
|
27
|
+
configured it makes one in the state folder. The robot gets a separate token for its voice
|
|
28
|
+
connection, and the check-in answers only the robot's own address.
|
|
29
|
+
|
|
30
|
+
AGPL-3.0-or-later.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "setuptools-scm>=8", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "seren-soma"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "The body's nervous system: a Stack-chan robot's voice, ears and touch, its faces' reactions, night mode and work hours."
|
|
9
|
+
license = "AGPL-3.0-or-later"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [{ name = "Chad Roesler" }]
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
keywords = ["seren", "stackchan", "robot", "voice", "xiaozhi", "aiohttp"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"aiohttp>=3.9",
|
|
16
|
+
# Opus in and out of the robot (libopus is in PyAV's wheels)
|
|
17
|
+
"av>=12",
|
|
18
|
+
"numpy>=1.24",
|
|
19
|
+
"pyyaml>=6.0",
|
|
20
|
+
# config blocks, token pointers, the viewer shell, enforce_server
|
|
21
|
+
"seren-meninges>=6.0.0,<7",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
dev = ["pytest>=8.0"]
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
seren-soma = "seren_soma.__main__:main"
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/ChadRoesler/SerenSoma"
|
|
32
|
+
Repository = "https://github.com/ChadRoesler/SerenSoma"
|
|
33
|
+
"Bug Tracker" = "https://github.com/ChadRoesler/SerenSoma/issues"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["."]
|
|
37
|
+
include = ["seren_soma*"]
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.package-data]
|
|
40
|
+
seren_soma = ["viewer/ui/*.html", "viewer/ui/*.css", "viewer/ui/*.js"]
|
|
41
|
+
|
|
42
|
+
[tool.pytest.ini_options]
|
|
43
|
+
testpaths = ["tests"]
|
|
44
|
+
|
|
45
|
+
[tool.setuptools_scm]
|
|
46
|
+
root = ".."
|
|
47
|
+
version_scheme = "release-branch-semver"
|
|
48
|
+
version_file = "seren_soma/_version.py"
|
|
49
|
+
tag_regex = "^v(?P<version>[0-9]+\\.[0-9]+\\.[0-9]+.*)$"
|
|
50
|
+
fallback_version = "0.0.0.dev0"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# ════════════════════════════════════════════════════════════════════════
|
|
2
|
+
# seren-soma.yaml - copy to ~/seren-soma/seren-soma.yaml
|
|
3
|
+
# ════════════════════════════════════════════════════════════════════════
|
|
4
|
+
|
|
5
|
+
server:
|
|
6
|
+
host: 0.0.0.0 # the robot dials in over the LAN
|
|
7
|
+
port: 7480
|
|
8
|
+
# The API token. Blank: the file `token` in the state folder, made the first time.
|
|
9
|
+
# bearer_token_env: SEREN_SOMA_TOKEN
|
|
10
|
+
|
|
11
|
+
# Tokens, what was heard, touches, settings and the log. Outside any repo.
|
|
12
|
+
state_dir: ~/seren-soma/state
|
|
13
|
+
|
|
14
|
+
# This box's address as the robot reaches it. Blank: the address this box uses toward the robot.
|
|
15
|
+
# advertise: 192.168.0.10
|
|
16
|
+
|
|
17
|
+
voice: wren # the voice Lodestar speaks in
|
|
18
|
+
idle_close_seconds: 60 # an open channel with no words this long hangs up
|
|
19
|
+
|
|
20
|
+
robot:
|
|
21
|
+
url: http://192.168.0.201:8080
|
|
22
|
+
# Its control token (token: in the robot's soma.yaml). Blank: the file
|
|
23
|
+
# `control_token` in the state folder. Or token_env / token_keyring / token_file / token.
|
|
24
|
+
# The check-in only answers the robot's own address; add others if it reaches you through one:
|
|
25
|
+
# device_from: [192.168.0.201]
|
|
26
|
+
|
|
27
|
+
lodestar:
|
|
28
|
+
# Hearing and speaking. Blank url: read from the Symposium config on this box.
|
|
29
|
+
# url: http://nuc:6361
|
|
30
|
+
# token_env: SEREN_LODESTAR_TOKEN
|
|
31
|
+
symposium_yaml: ~/seren/wren/apps/symposium/seren-symposium.yaml
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""seren_soma - the body's nervous system.
|
|
2
|
+
|
|
3
|
+
A Stack-chan robot running SerenSoma's firmware checks in here and speaks over a websocket: what it
|
|
4
|
+
hears goes to Lodestar to be transcribed, what the mind says comes back through Lodestar in its voice.
|
|
5
|
+
This server also reads the robot's head sensor into strokes, pokes, scritches and resting hands, picks
|
|
6
|
+
the face each one brings up, and owns night mode and work hours, so the body behaves itself with
|
|
7
|
+
nothing else running.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
try: # the setuptools-scm build artifact (gitignored); present in installed wheels
|
|
12
|
+
from ._version import version as __version__
|
|
13
|
+
except Exception: # source checkout without a build -> metadata, then dev fallback
|
|
14
|
+
try:
|
|
15
|
+
from importlib.metadata import version as _v
|
|
16
|
+
|
|
17
|
+
__version__ = _v("seren-soma")
|
|
18
|
+
except Exception:
|
|
19
|
+
__version__ = "0.0.0.dev0"
|
|
20
|
+
|
|
21
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Entry point for `python -m seren_soma` or the `seren-soma` script.
|
|
2
|
+
|
|
3
|
+
--describe answers before anything heavy is imported. --config like the rest of the family;
|
|
4
|
+
--advertise and --state override the config for a hand run.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import sys
|
|
12
|
+
from logging.handlers import RotatingFileHandler
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _force_utf8_stdio() -> None:
|
|
17
|
+
for stream in (sys.stdout, sys.stderr):
|
|
18
|
+
try:
|
|
19
|
+
stream.reconfigure(encoding="utf-8") # type: ignore[union-attr]
|
|
20
|
+
except (AttributeError, ValueError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main() -> None:
|
|
25
|
+
_force_utf8_stdio()
|
|
26
|
+
if "--describe" in sys.argv[1:]:
|
|
27
|
+
from ._describe import DESCRIBE
|
|
28
|
+
print(json.dumps(DESCRIBE))
|
|
29
|
+
raise SystemExit(0)
|
|
30
|
+
|
|
31
|
+
parser = argparse.ArgumentParser(prog="seren_soma", description="SerenSoma - the body's nervous system.")
|
|
32
|
+
parser.add_argument("--config", "-c", default=None,
|
|
33
|
+
help="Path to seren-soma.yaml (default: $SEREN_SOMA_CONFIG, then ~/seren-soma/seren-soma.yaml).")
|
|
34
|
+
parser.add_argument("--advertise", default=None, help="This box's address as the robot reaches it.")
|
|
35
|
+
parser.add_argument("--state", default=None, help="The state folder (tokens, what was heard, the log).")
|
|
36
|
+
args = parser.parse_args()
|
|
37
|
+
|
|
38
|
+
from aiohttp import web
|
|
39
|
+
from seren_meninges.exposure import enforce_server
|
|
40
|
+
|
|
41
|
+
from . import __version__, voice
|
|
42
|
+
from ._describe import ACCENT
|
|
43
|
+
from ._diag import diag
|
|
44
|
+
from .config import load_config
|
|
45
|
+
|
|
46
|
+
cfg = load_config(args.config)
|
|
47
|
+
if args.advertise:
|
|
48
|
+
cfg.advertise = args.advertise
|
|
49
|
+
if args.state:
|
|
50
|
+
cfg.state_dir = args.state
|
|
51
|
+
cfg.state.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
|
|
53
|
+
# the log goes to stderr (journalctl, NSSM) and to a file the viewer can show
|
|
54
|
+
fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
|
|
55
|
+
handlers = [logging.StreamHandler(), RotatingFileHandler(cfg.state / "seren-soma.log", maxBytes=1_000_000,
|
|
56
|
+
backupCount=3, encoding="utf-8")]
|
|
57
|
+
for h in handlers:
|
|
58
|
+
h.setFormatter(fmt)
|
|
59
|
+
logging.basicConfig(level=logging.INFO, handlers=handlers)
|
|
60
|
+
logging.getLogger("aiohttp.access").setLevel(logging.WARNING)
|
|
61
|
+
|
|
62
|
+
rt = cfg.runtime()
|
|
63
|
+
# LAN by nature, so the API token is required; runtime() made one if none was configured
|
|
64
|
+
enforce_server(cfg.server, service="seren-soma", env_prefix="SEREN_SOMA", log=diag)
|
|
65
|
+
|
|
66
|
+
html = ""
|
|
67
|
+
try:
|
|
68
|
+
from seren_meninges.viewer import render_from_dir
|
|
69
|
+
html = render_from_dir(Path(__file__).parent / "viewer" / "ui", title="SerenSoma", brand="Seren<b>Soma</b>",
|
|
70
|
+
subtitle=f"v{__version__} · the body's nervous system", accent=ACCENT)
|
|
71
|
+
except Exception as exc: # noqa: BLE001 - the body runs without its page
|
|
72
|
+
diag(f"[seren-soma] no viewer ({exc}); the body runs without its page")
|
|
73
|
+
|
|
74
|
+
link = voice.Link(rt)
|
|
75
|
+
diag(f"[seren-soma] on {rt.host}:{rt.port}, the robot at {rt.robot_url}, telling it to call {rt.advertise}")
|
|
76
|
+
diag(f"[seren-soma] viewer at http://{rt.advertise}:{rt.port}/viewer; state in {cfg.state}")
|
|
77
|
+
web.run_app(voice.make_app(link, html), host=rt.host, port=rt.port, print=None)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
if __name__ == "__main__":
|
|
81
|
+
main()
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""SerenSoma's identity card. STDLIB ONLY - nothing imported, nothing read: the moment you most want
|
|
2
|
+
a thing to say its own name is when its install is broken."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
NAME = "seren-soma"
|
|
6
|
+
DISPLAY = "Seren Soma"
|
|
7
|
+
DESCRIPTION = ("The body's nervous system: a Stack-chan robot's voice, ears and touch, its faces' "
|
|
8
|
+
"reactions, night mode and work hours.")
|
|
9
|
+
|
|
10
|
+
# 7480: outside the family's 74xx band on purpose, where the robot's firmware has always found it.
|
|
11
|
+
PORT = 7480
|
|
12
|
+
|
|
13
|
+
GROUP = "auxiliary"
|
|
14
|
+
|
|
15
|
+
# Sage: the sweater the face wears.
|
|
16
|
+
ACCENT = "#8fbf88"
|
|
17
|
+
|
|
18
|
+
# Lodestar does the hearing and speaking; without it the body still reacts to touch and keeps night.
|
|
19
|
+
REQUIRES: tuple = ()
|
|
20
|
+
EXTRAS: tuple = ()
|
|
21
|
+
|
|
22
|
+
DESCRIBE = {
|
|
23
|
+
"schema_version": 1,
|
|
24
|
+
"name": NAME,
|
|
25
|
+
"display": DISPLAY,
|
|
26
|
+
"description": DESCRIPTION,
|
|
27
|
+
"port": PORT,
|
|
28
|
+
"group": GROUP,
|
|
29
|
+
"accent": ACCENT,
|
|
30
|
+
"package": "seren-soma",
|
|
31
|
+
"requires": list(REQUIRES),
|
|
32
|
+
"extras": list(EXTRAS),
|
|
33
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Startup diagnostics that survive a nulled stdout (parity with the family's _diag): `pythonw` nulls
|
|
2
|
+
sys.stdout, and a write to a closed stream would end the run."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def diag(message: str) -> None:
|
|
9
|
+
for stream in (sys.stdout, sys.stderr):
|
|
10
|
+
try:
|
|
11
|
+
if stream is None:
|
|
12
|
+
continue
|
|
13
|
+
stream.write(message + "\n")
|
|
14
|
+
stream.flush()
|
|
15
|
+
return
|
|
16
|
+
except Exception: # noqa: BLE001 - a broken stream must not be fatal
|
|
17
|
+
continue
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '1.0.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 0, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = 'gccb98edb7'
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""SerenSoma's config: dataclasses on the shared Meninges blocks.
|
|
2
|
+
|
|
3
|
+
Read from, first found wins:
|
|
4
|
+
|
|
5
|
+
--config -> $SEREN_SOMA_CONFIG -> ~/seren-soma/seren-soma.yaml -> defaults
|
|
6
|
+
|
|
7
|
+
It binds 0.0.0.0 by default: the robot dials in over the LAN, so loopback would be a body with no
|
|
8
|
+
nervous system. That makes the API token mandatory (Meninges' enforce_server), and when no
|
|
9
|
+
server.bearer_token_* pointer is set it's the one in <state>/token, made the first time.
|
|
10
|
+
|
|
11
|
+
The robot's control token and Lodestar's are POINTERS too: `*_env` (an env var's name), `*_keyring`
|
|
12
|
+
("service/username"), `*_file` (a file holding only the token), or inline as the escape hatch. With no
|
|
13
|
+
Lodestar given, it's read from the Symposium config on this box, as it always was.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import socket
|
|
19
|
+
from argparse import Namespace
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, Dict, List, Optional
|
|
23
|
+
from urllib.parse import urlparse
|
|
24
|
+
|
|
25
|
+
from seren_meninges import ServerConfig, resolve_token
|
|
26
|
+
|
|
27
|
+
from ._describe import PORT as DEFAULT_PORT
|
|
28
|
+
from ._diag import diag
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
import yaml
|
|
32
|
+
_HAS_YAML = True
|
|
33
|
+
except ImportError: # pragma: no cover - pyyaml is a dependency
|
|
34
|
+
_HAS_YAML = False
|
|
35
|
+
|
|
36
|
+
DEFAULT_HOST = "0.0.0.0"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Pointer:
|
|
41
|
+
"""Where a token is: a file, an env var's name, a keychain ref, or inline."""
|
|
42
|
+
token: str = field(default="", repr=False)
|
|
43
|
+
token_env: str = ""
|
|
44
|
+
token_keyring: str = ""
|
|
45
|
+
token_file: str = ""
|
|
46
|
+
|
|
47
|
+
def resolve(self, fallback_file: Optional[Path] = None) -> str:
|
|
48
|
+
path = self.token_file or (str(fallback_file) if fallback_file and not (self.token or self.token_env or self.token_keyring) else "")
|
|
49
|
+
if path:
|
|
50
|
+
try:
|
|
51
|
+
found = Path(os.path.expanduser(path)).read_text(encoding="utf-8").strip()
|
|
52
|
+
if found:
|
|
53
|
+
return found
|
|
54
|
+
except OSError:
|
|
55
|
+
if self.token_file:
|
|
56
|
+
diag(f"[seren-soma] can't read the token file {path}")
|
|
57
|
+
return resolve_token(inline=self.token or None, keyring_ref=self.token_keyring or None,
|
|
58
|
+
env_var=self.token_env or None)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_dict(cls, d: Any) -> "Pointer":
|
|
62
|
+
d = d if isinstance(d, dict) else {}
|
|
63
|
+
return cls(token=str(d.get("token") or ""), token_env=str(d.get("token_env") or ""),
|
|
64
|
+
token_keyring=str(d.get("token_keyring") or ""), token_file=str(d.get("token_file") or ""))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class RobotConfig:
|
|
69
|
+
url: str = "http://192.168.0.201:8080"
|
|
70
|
+
auth: Pointer = field(default_factory=Pointer) # its control token; default <state>/control_token
|
|
71
|
+
# Who /ota/ answers. Empty: the robot's own address, looked up from url at startup.
|
|
72
|
+
device_from: List[str] = field(default_factory=list)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class LodestarConfig:
|
|
77
|
+
url: str = "" # blank: from symposium_yaml
|
|
78
|
+
auth: Pointer = field(default_factory=Pointer)
|
|
79
|
+
symposium_yaml: str = "~/seren/wren/apps/symposium/seren-symposium.yaml"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class SomaConfig:
|
|
84
|
+
server: ServerConfig = field(default_factory=lambda: ServerConfig(host=DEFAULT_HOST, port=DEFAULT_PORT))
|
|
85
|
+
state_dir: str = "~/seren-soma/state"
|
|
86
|
+
advertise: str = "" # this box as the robot reaches it; blank: worked out at startup
|
|
87
|
+
voice: str = "wren" # the voice Lodestar speaks in
|
|
88
|
+
idle_close_seconds: float = 60.0
|
|
89
|
+
updates: bool = True # "is there a newer seren-soma", checked against PyPI
|
|
90
|
+
robot: RobotConfig = field(default_factory=RobotConfig)
|
|
91
|
+
lodestar: LodestarConfig = field(default_factory=LodestarConfig)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def state(self) -> Path:
|
|
95
|
+
return Path(os.path.expanduser(self.state_dir)).resolve()
|
|
96
|
+
|
|
97
|
+
def runtime(self) -> Namespace:
|
|
98
|
+
"""Everything the server needs, resolved: tokens read, addresses worked out. Raises SystemExit
|
|
99
|
+
with the reason when something it can't run without is missing."""
|
|
100
|
+
from .voice import lodestar_from_symposium, token_file, use_state
|
|
101
|
+
use_state(self.state)
|
|
102
|
+
api = self.server.resolve_bearer()
|
|
103
|
+
if not api:
|
|
104
|
+
# the default: a token of its own in the state folder, made the first time
|
|
105
|
+
api = token_file("token")
|
|
106
|
+
self.server.bearer_token = api
|
|
107
|
+
robot_host = urlparse(self.robot.url).hostname or ""
|
|
108
|
+
device_from = set(self.robot.device_from)
|
|
109
|
+
if not device_from and robot_host:
|
|
110
|
+
try:
|
|
111
|
+
device_from = {socket.gethostbyname(robot_host)}
|
|
112
|
+
except OSError:
|
|
113
|
+
diag(f"[seren-soma] can't look up the robot's address {robot_host}; the check-in will answer anyone")
|
|
114
|
+
if self.lodestar.url:
|
|
115
|
+
lodestar_url, lodestar_token = self.lodestar.url, self.lodestar.auth.resolve()
|
|
116
|
+
else:
|
|
117
|
+
lodestar_url, lodestar_token = lodestar_from_symposium(Path(os.path.expanduser(self.lodestar.symposium_yaml)))
|
|
118
|
+
return Namespace(
|
|
119
|
+
host=self.server.host, port=self.server.port, advertise=self.advertise or _this_box(robot_host),
|
|
120
|
+
voice=self.voice, device=robot_host, updates=self.updates, robot_url=self.robot.url, idle_close=self.idle_close_seconds,
|
|
121
|
+
api_token=api, device_token=token_file("device_token"),
|
|
122
|
+
robot_token=self.robot.auth.resolve(self.state / "control_token"), device_from=device_from,
|
|
123
|
+
lodestar_url=lodestar_url.rstrip("/"), lodestar_token=lodestar_token)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _this_box(toward: str) -> str:
|
|
127
|
+
"""The address this box uses to reach the robot, which is the one the robot can reach it on."""
|
|
128
|
+
try:
|
|
129
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
|
130
|
+
s.connect((toward or "192.168.0.1", 9))
|
|
131
|
+
return s.getsockname()[0]
|
|
132
|
+
except OSError:
|
|
133
|
+
return "127.0.0.1"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _candidate_paths(explicit: Optional[str]) -> List[Path]:
|
|
137
|
+
out: List[Path] = []
|
|
138
|
+
if explicit:
|
|
139
|
+
out.append(Path(explicit))
|
|
140
|
+
env = os.environ.get("SEREN_SOMA_CONFIG")
|
|
141
|
+
if env:
|
|
142
|
+
out.append(Path(env))
|
|
143
|
+
out.append(Path.home() / "seren-soma" / "seren-soma.yaml")
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _read_yaml(path: Optional[str]) -> Dict[str, Any]:
|
|
148
|
+
for candidate in _candidate_paths(path):
|
|
149
|
+
if not candidate.is_file():
|
|
150
|
+
continue
|
|
151
|
+
if not _HAS_YAML:
|
|
152
|
+
diag(f"[seren-soma] pyyaml missing; ignoring {candidate}")
|
|
153
|
+
return {}
|
|
154
|
+
try:
|
|
155
|
+
loaded = yaml.safe_load(candidate.read_text(encoding="utf-8")) or {}
|
|
156
|
+
if not isinstance(loaded, dict):
|
|
157
|
+
raise ValueError("top level of the config is not a mapping")
|
|
158
|
+
diag(f"[seren-soma] config: {candidate}")
|
|
159
|
+
return loaded
|
|
160
|
+
except Exception as exc: # noqa: BLE001 - lenient for a malformed file, and it says so
|
|
161
|
+
diag(f"[seren-soma] {candidate} is malformed ({exc}); falling back to defaults")
|
|
162
|
+
return {}
|
|
163
|
+
return {}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def load_config(path: Optional[str] = None) -> SomaConfig:
|
|
167
|
+
d = _read_yaml(path)
|
|
168
|
+
raw = d.get("server")
|
|
169
|
+
cfg = SomaConfig(server=ServerConfig.from_dict(raw if isinstance(raw, dict) else {}, default_port=DEFAULT_PORT,
|
|
170
|
+
default_host=DEFAULT_HOST))
|
|
171
|
+
cfg.state_dir = str(d.get("state_dir") or cfg.state_dir)
|
|
172
|
+
cfg.advertise = str(d.get("advertise") or "")
|
|
173
|
+
cfg.voice = str(d.get("voice") or cfg.voice)
|
|
174
|
+
up = d.get("updates")
|
|
175
|
+
cfg.updates = bool(up.get("enabled", True)) if isinstance(up, dict) else (bool(up) if up is not None else True)
|
|
176
|
+
try:
|
|
177
|
+
cfg.idle_close_seconds = float(d.get("idle_close_seconds", cfg.idle_close_seconds))
|
|
178
|
+
except (TypeError, ValueError):
|
|
179
|
+
pass
|
|
180
|
+
r = d.get("robot") if isinstance(d.get("robot"), dict) else {}
|
|
181
|
+
cfg.robot = RobotConfig(url=str(r.get("url") or RobotConfig.url), auth=Pointer.from_dict(r),
|
|
182
|
+
device_from=[str(x) for x in (r.get("device_from") or [])])
|
|
183
|
+
lo = d.get("lodestar") if isinstance(d.get("lodestar"), dict) else {}
|
|
184
|
+
cfg.lodestar = LodestarConfig(url=str(lo.get("url") or ""), auth=Pointer.from_dict(lo),
|
|
185
|
+
symposium_yaml=str(lo.get("symposium_yaml") or LodestarConfig.symposium_yaml))
|
|
186
|
+
if v := os.environ.get("SEREN_SOMA_ADVERTISE"):
|
|
187
|
+
cfg.advertise = v
|
|
188
|
+
if v := os.environ.get("SEREN_SOMA_STATE_DIR"):
|
|
189
|
+
cfg.state_dir = v
|
|
190
|
+
return cfg
|