chromapi 1.0.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.
Files changed (219) hide show
  1. chromapi/__init__.py +2 -0
  2. chromapi/__main__.py +6 -0
  3. chromapi/assets/audio/alert.wav +0 -0
  4. chromapi/assets/audio/chromapi_scream.wav +0 -0
  5. chromapi/assets/audio/confused.wav +0 -0
  6. chromapi/assets/audio/dizzy.wav +0 -0
  7. chromapi/assets/audio/excited.wav +0 -0
  8. chromapi/assets/audio/greeting.wav +0 -0
  9. chromapi/assets/audio/happy.wav +0 -0
  10. chromapi/assets/audio/no.wav +0 -0
  11. chromapi/assets/audio/purring.wav +0 -0
  12. chromapi/assets/audio/sad.wav +0 -0
  13. chromapi/assets/audio/scared.wav +0 -0
  14. chromapi/assets/audio/sleepy.wav +0 -0
  15. chromapi/assets/audio/squeak.wav +0 -0
  16. chromapi/assets/audio/surprised.wav +0 -0
  17. chromapi/assets/audio/thinking.wav +0 -0
  18. chromapi/assets/audio/upset.wav +0 -0
  19. chromapi/assets/audio/yes.wav +0 -0
  20. chromapi/assets/favicon.ico +0 -0
  21. chromapi/assets/firmware/chromapi_stm32_core_v2.0.0.hex +2222 -0
  22. chromapi/assets/firmware/flash.sh +88 -0
  23. chromapi/assets/moves/README.md +48 -0
  24. chromapi/assets/moves/angry.json +1 -0
  25. chromapi/assets/moves/confused.json +1 -0
  26. chromapi/assets/moves/dizzy.json +1 -0
  27. chromapi/assets/moves/excited.json +1 -0
  28. chromapi/assets/moves/greeting.json +1 -0
  29. chromapi/assets/moves/happy.json +1 -0
  30. chromapi/assets/moves/joy.json +1 -0
  31. chromapi/assets/moves/kick.json +1 -0
  32. chromapi/assets/moves/metadata.jsonl +15 -0
  33. chromapi/assets/moves/no.json +1 -0
  34. chromapi/assets/moves/purring.json +1 -0
  35. chromapi/assets/moves/sad.json +1 -0
  36. chromapi/assets/moves/scared.json +1 -0
  37. chromapi/assets/moves/surprised.json +1 -0
  38. chromapi/assets/moves/tired.json +1 -0
  39. chromapi/assets/moves/yes.json +1 -0
  40. chromapi/chromapi.py +1460 -0
  41. chromapi/cli.py +106 -0
  42. chromapi/config/config.yaml +118 -0
  43. chromapi/estimation/__init__.py +6 -0
  44. chromapi/estimation/attitude.py +107 -0
  45. chromapi/hardware/__init__.py +2 -0
  46. chromapi/hardware/battery.py +54 -0
  47. chromapi/hardware/fan.py +165 -0
  48. chromapi/hardware/motherboard_bridge.py +345 -0
  49. chromapi/input/__init__.py +2 -0
  50. chromapi/input/gamepad.py +379 -0
  51. chromapi/input/pairing.py +98 -0
  52. chromapi/kinematics/__init__.py +10 -0
  53. chromapi/kinematics/kromatics.py +324 -0
  54. chromapi/kinematics/poses.py +29 -0
  55. chromapi/kinematics/topology.py +26 -0
  56. chromapi/kinematics/types.py +21 -0
  57. chromapi/locomotion/__init__.py +7 -0
  58. chromapi/locomotion/balance.py +284 -0
  59. chromapi/locomotion/gait.py +595 -0
  60. chromapi/locomotion/recorded_move.py +290 -0
  61. chromapi/media/__init__.py +2 -0
  62. chromapi/media/audio.py +424 -0
  63. chromapi/media/led.py +461 -0
  64. chromapi/model/LICENSE +438 -0
  65. chromapi/model/mjcf/additional.xml +21 -0
  66. chromapi/model/mjcf/assets/18650_li_ion_battery.msh +0 -0
  67. chromapi/model/mjcf/assets/18650_li_ion_battery.part +13 -0
  68. chromapi/model/mjcf/assets/battery_holder.msh +0 -0
  69. chromapi/model/mjcf/assets/battery_holder.part +13 -0
  70. chromapi/model/mjcf/assets/camera_imx219_d160.msh +0 -0
  71. chromapi/model/mjcf/assets/camera_imx219_d160.part +13 -0
  72. chromapi/model/mjcf/assets/chromapi_logo.msh +0 -0
  73. chromapi/model/mjcf/assets/chromapi_logo.part +13 -0
  74. chromapi/model/mjcf/assets/chromapi_logo_circle.msh +0 -0
  75. chromapi/model/mjcf/assets/chromapi_logo_inner.msh +0 -0
  76. chromapi/model/mjcf/assets/chromapi_logo_outer.msh +0 -0
  77. chromapi/model/mjcf/assets/chromapi_motherboard.msh +0 -0
  78. chromapi/model/mjcf/assets/chromapi_motherboard.part +13 -0
  79. chromapi/model/mjcf/assets/composant2_1__corps1.msh +0 -0
  80. chromapi/model/mjcf/assets/composant2_1__corps1.part +13 -0
  81. chromapi/model/mjcf/assets/composant3_1__corps1.msh +0 -0
  82. chromapi/model/mjcf/assets/composant3_1__corps1.part +13 -0
  83. chromapi/model/mjcf/assets/composant4_1__corps1.msh +0 -0
  84. chromapi/model/mjcf/assets/composant4_1__corps1.part +13 -0
  85. chromapi/model/mjcf/assets/connector_f_1__corps1.msh +0 -0
  86. chromapi/model/mjcf/assets/connector_f_1__corps1.part +13 -0
  87. chromapi/model/mjcf/assets/connector_f_1__corps1_1.msh +0 -0
  88. chromapi/model/mjcf/assets/connector_f_1__corps1_1.part +13 -0
  89. chromapi/model/mjcf/assets/corps14.msh +0 -0
  90. chromapi/model/mjcf/assets/corps14.part +13 -0
  91. chromapi/model/mjcf/assets/fan_nf_a4x10.msh +0 -0
  92. chromapi/model/mjcf/assets/fan_nf_a4x10.part +13 -0
  93. chromapi/model/mjcf/assets/foot.msh +0 -0
  94. chromapi/model/mjcf/assets/foot.part +13 -0
  95. chromapi/model/mjcf/assets/left_coxa.msh +0 -0
  96. chromapi/model/mjcf/assets/left_coxa.part +13 -0
  97. chromapi/model/mjcf/assets/left_femur.msh +0 -0
  98. chromapi/model/mjcf/assets/left_femur.part +13 -0
  99. chromapi/model/mjcf/assets/left_tibia.msh +0 -0
  100. chromapi/model/mjcf/assets/left_tibia.part +13 -0
  101. chromapi/model/mjcf/assets/microswitch.msh +0 -0
  102. chromapi/model/mjcf/assets/microswitch.part +13 -0
  103. chromapi/model/mjcf/assets/power_switch.msh +0 -0
  104. chromapi/model/mjcf/assets/power_switch.part +13 -0
  105. chromapi/model/mjcf/assets/raspberry_pi_4_model_b.msh +0 -0
  106. chromapi/model/mjcf/assets/raspberry_pi_4_model_b.part +13 -0
  107. chromapi/model/mjcf/assets/right_coxa.msh +0 -0
  108. chromapi/model/mjcf/assets/right_coxa.part +13 -0
  109. chromapi/model/mjcf/assets/right_femur.msh +0 -0
  110. chromapi/model/mjcf/assets/right_femur.part +13 -0
  111. chromapi/model/mjcf/assets/right_tibia.msh +0 -0
  112. chromapi/model/mjcf/assets/right_tibia.part +13 -0
  113. chromapi/model/mjcf/assets/robot_case_bottom.msh +0 -0
  114. chromapi/model/mjcf/assets/robot_case_bottom.part +13 -0
  115. chromapi/model/mjcf/assets/robot_case_top.msh +0 -0
  116. chromapi/model/mjcf/assets/robot_case_top.part +13 -0
  117. chromapi/model/mjcf/assets/rpi_battery_bracket.msh +0 -0
  118. chromapi/model/mjcf/assets/rpi_battery_bracket.part +13 -0
  119. chromapi/model/mjcf/assets/speaker.msh +0 -0
  120. chromapi/model/mjcf/assets/speaker.part +13 -0
  121. chromapi/model/mjcf/assets/vis_1__corps1.msh +0 -0
  122. chromapi/model/mjcf/assets/vis_1__corps1.part +13 -0
  123. chromapi/model/mjcf/assets/vis_1__corps1_1.msh +0 -0
  124. chromapi/model/mjcf/assets/vis_1__corps1_1.part +13 -0
  125. chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.msh +0 -0
  126. chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
  127. chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.msh +0 -0
  128. chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
  129. chromapi/model/mjcf/config.json +14 -0
  130. chromapi/model/mjcf/robot.xml +639 -0
  131. chromapi/model/mjcf/scene.xml +24 -0
  132. chromapi/model/urdf/assets/18650_li_ion_battery.part +13 -0
  133. chromapi/model/urdf/assets/18650_li_ion_battery.stl +0 -0
  134. chromapi/model/urdf/assets/battery_holder.part +13 -0
  135. chromapi/model/urdf/assets/battery_holder.stl +0 -0
  136. chromapi/model/urdf/assets/camera_imx219_d160.part +13 -0
  137. chromapi/model/urdf/assets/camera_imx219_d160.stl +0 -0
  138. chromapi/model/urdf/assets/chromapi_logo.part +13 -0
  139. chromapi/model/urdf/assets/chromapi_logo.stl +0 -0
  140. chromapi/model/urdf/assets/chromapi_logo_circle.stl +0 -0
  141. chromapi/model/urdf/assets/chromapi_logo_inner.stl +0 -0
  142. chromapi/model/urdf/assets/chromapi_logo_outer.stl +0 -0
  143. chromapi/model/urdf/assets/chromapi_motherboard.part +13 -0
  144. chromapi/model/urdf/assets/chromapi_motherboard.stl +0 -0
  145. chromapi/model/urdf/assets/composant2_1__corps1.part +13 -0
  146. chromapi/model/urdf/assets/composant2_1__corps1.stl +0 -0
  147. chromapi/model/urdf/assets/composant3_1__corps1.part +13 -0
  148. chromapi/model/urdf/assets/composant3_1__corps1.stl +0 -0
  149. chromapi/model/urdf/assets/composant4_1__corps1.part +13 -0
  150. chromapi/model/urdf/assets/composant4_1__corps1.stl +0 -0
  151. chromapi/model/urdf/assets/connector_f_1__corps1.part +13 -0
  152. chromapi/model/urdf/assets/connector_f_1__corps1.stl +0 -0
  153. chromapi/model/urdf/assets/connector_f_1__corps1_1.part +13 -0
  154. chromapi/model/urdf/assets/connector_f_1__corps1_1.stl +0 -0
  155. chromapi/model/urdf/assets/corps14.part +13 -0
  156. chromapi/model/urdf/assets/corps14.stl +0 -0
  157. chromapi/model/urdf/assets/fan_nf_a4x10.part +13 -0
  158. chromapi/model/urdf/assets/fan_nf_a4x10.stl +0 -0
  159. chromapi/model/urdf/assets/foot.part +13 -0
  160. chromapi/model/urdf/assets/foot.stl +0 -0
  161. chromapi/model/urdf/assets/left_coxa.part +13 -0
  162. chromapi/model/urdf/assets/left_coxa.stl +0 -0
  163. chromapi/model/urdf/assets/left_femur.part +13 -0
  164. chromapi/model/urdf/assets/left_femur.stl +0 -0
  165. chromapi/model/urdf/assets/left_tibia.part +13 -0
  166. chromapi/model/urdf/assets/left_tibia.stl +0 -0
  167. chromapi/model/urdf/assets/microswitch.part +13 -0
  168. chromapi/model/urdf/assets/microswitch.stl +0 -0
  169. chromapi/model/urdf/assets/power_switch.part +13 -0
  170. chromapi/model/urdf/assets/power_switch.stl +0 -0
  171. chromapi/model/urdf/assets/raspberry_pi_4_model_b.part +13 -0
  172. chromapi/model/urdf/assets/raspberry_pi_4_model_b.stl +0 -0
  173. chromapi/model/urdf/assets/right_coxa.part +13 -0
  174. chromapi/model/urdf/assets/right_coxa.stl +0 -0
  175. chromapi/model/urdf/assets/right_femur.part +13 -0
  176. chromapi/model/urdf/assets/right_femur.stl +0 -0
  177. chromapi/model/urdf/assets/right_tibia.part +13 -0
  178. chromapi/model/urdf/assets/right_tibia.stl +0 -0
  179. chromapi/model/urdf/assets/robot_case_bottom.part +13 -0
  180. chromapi/model/urdf/assets/robot_case_bottom.stl +0 -0
  181. chromapi/model/urdf/assets/robot_case_top.part +13 -0
  182. chromapi/model/urdf/assets/robot_case_top.stl +0 -0
  183. chromapi/model/urdf/assets/rpi_battery_bracket.part +13 -0
  184. chromapi/model/urdf/assets/rpi_battery_bracket.stl +0 -0
  185. chromapi/model/urdf/assets/speaker.part +13 -0
  186. chromapi/model/urdf/assets/speaker.stl +0 -0
  187. chromapi/model/urdf/assets/vis_1__corps1.part +13 -0
  188. chromapi/model/urdf/assets/vis_1__corps1.stl +0 -0
  189. chromapi/model/urdf/assets/vis_1__corps1_1.part +13 -0
  190. chromapi/model/urdf/assets/vis_1__corps1_1.stl +0 -0
  191. chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
  192. chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.stl +0 -0
  193. chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
  194. chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.stl +0 -0
  195. chromapi/model/urdf/config.json +8 -0
  196. chromapi/model/urdf/robot.urdf +2587 -0
  197. chromapi/utils/calibrate_imu_mount.py +80 -0
  198. chromapi/utils/calibrate_servo_centers.py +432 -0
  199. chromapi/utils/flash.py +141 -0
  200. chromapi/utils/health.py +210 -0
  201. chromapi/utils/report.py +75 -0
  202. chromapi/utils/setup_motors.py +189 -0
  203. chromapi/utils/sim_server.py +126 -0
  204. chromapi/web/__init__.py +2 -0
  205. chromapi/web/access.py +167 -0
  206. chromapi/web/app.py +1136 -0
  207. chromapi/web/camera.py +202 -0
  208. chromapi/web/static/fonts/varela-round.woff2 +0 -0
  209. chromapi/web/static/index.html +1079 -0
  210. chromapi/web/static/logo.png +0 -0
  211. chromapi/web/static/motherboard_front.png +0 -0
  212. chromapi/web/static/socket.io.min.js +7 -0
  213. chromapi-1.0.0.dist-info/METADATA +222 -0
  214. chromapi-1.0.0.dist-info/RECORD +219 -0
  215. chromapi-1.0.0.dist-info/WHEEL +5 -0
  216. chromapi-1.0.0.dist-info/entry_points.txt +2 -0
  217. chromapi-1.0.0.dist-info/licenses/LICENSE +201 -0
  218. chromapi-1.0.0.dist-info/licenses/src/chromapi/model/LICENSE +438 -0
  219. chromapi-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,290 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Recorded moves: trajectories stored as files and played back.
3
+
4
+ Each sample of a recorded move holds either:
5
+
6
+ - ``body``: the chassis pose over the planted feet (:class:`RecordedMove`);
7
+ - ``leg``: offsets of one front leg's 3 joints from where it starts (:class:`RecordedLegMove`), played after
8
+ shifting the weight onto the other three feet.
9
+
10
+ A library is a folder (the bundled ``assets/moves`` by default) or a Hugging Face dataset (``"<account>/<name>"``,
11
+ ``pip install 'chromapi[hub]'``), downloaded once then read from the cache, so it can be used offline.
12
+
13
+ Usage::
14
+
15
+ body = BalanceMove(dt=1.0 / robot.loop_hz)
16
+ moves = RecordedMoves() # or RecordedMoves("Mowibox/chromaposes")
17
+ robot.play_move(moves.get("yes", body))
18
+ robot.play_move(moves.get("greeting", body, leg="tr"))
19
+ """
20
+
21
+ import json
22
+ import logging
23
+ import math
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional, Tuple, Union
26
+
27
+ import numpy as np
28
+
29
+ from chromapi.chromapi import MotorCommand, Move, RobotState
30
+ from chromapi.locomotion.balance import BalanceMove
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ MOVES_DIR = Path(__file__).resolve().parent.parent / "assets" / "moves"
35
+ SETTLE_S = 0.4 # [s] back to the start pose before done
36
+
37
+ # What check_move lets through (the bundled moves stay well within: 3 s, 0.22 m/s, 1.4 rad/s, leg 4.7 rad/s)
38
+ MAX_FILE_BYTES = 256_000
39
+ MAX_DURATION_S = 60.0 # [s]
40
+ MIN_STEP_S = 0.005 # [s] between samples
41
+ MAX_SHIFT_M = 0.03 # [m] |x|, |y|, |z| of a body move
42
+ MAX_TILT_RAD = 0.2 # [rad] |roll|, |pitch|, |yaw|
43
+ MAX_SHIFT_SPEED_MPS = 0.3 # [m.s⁻¹]
44
+ MAX_TILT_SPEED_RAD_S = 2.0 # [rad.s⁻¹]
45
+ MAX_LEG_RAD = 1.2 # [rad] leg joint offsets; the joint limits are applied on top while playing
46
+ MAX_LEG_SPEED_RAD_S = 6.0 # [rad.s⁻¹]
47
+ _KEYS = {"description", "time", "set_target_data", "default_leg", "mood"}
48
+
49
+ # Weight shift onto the 3 other feet, for a leg move
50
+ EMOTE_COM_MARGIN_M = 0.03 # [m] CoM inside the support triangle
51
+ EMOTE_MAX_SHIFT_M = 0.05 # [m] foot workspace limit
52
+ EMOTE_SHIFT_S = 0.5 # [s]
53
+ EMOTE_LAND_S = 0.3 # [s] 4 feet down before shifting back
54
+ EMOTE_MAX_TILT_DEG = 8.0 # [deg] steeper than this, no move starts
55
+
56
+ _DIAGONAL_LEG = {"tl": "br", "tr": "bl", "bl": "tr", "br": "tl"}
57
+
58
+ # Feet frame: +X forward, +Y left, +Z up [m]; roll > 0 right, pitch > 0 nose down, yaw > 0 left [rad].
59
+ Pose = Tuple[Tuple[float, float, float], Tuple[float, float, float]] # (xyz, rpy)
60
+
61
+
62
+ def _ease(t01: float) -> float:
63
+ """Cosine easing on [0, 1], zero speed at both ends."""
64
+ return 0.5 - 0.5 * math.cos(math.pi * min(max(t01, 0.0), 1.0))
65
+
66
+
67
+ def _numbers(values: Any, what: str) -> np.ndarray:
68
+ """``values`` as a float array, if it is a list of plain finite numbers."""
69
+ if not isinstance(values, list) or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
70
+ raise ValueError(f"{what}: not a list of numbers")
71
+ array = np.asarray(values, dtype=float)
72
+ if not np.all(np.isfinite(array)):
73
+ raise ValueError(f"{what}: not finite")
74
+ return array
75
+
76
+
77
+ def check_move(move: Any) -> None:
78
+ """Raise ValueError unless ``move`` (a parsed JSON) is a known, bounded move: see the MAX_* limits."""
79
+ if not isinstance(move, dict) or set(move) - _KEYS:
80
+ raise ValueError(f"unknown keys {sorted(set(move) - _KEYS) if isinstance(move, dict) else move!r}")
81
+ if not isinstance(move.get("description"), str) or not 0 < len(move["description"]) <= 500:
82
+ raise ValueError("description: a text of 1 to 500 characters")
83
+ if "mood" in move and not isinstance(move["mood"], str):
84
+ raise ValueError("mood: a mood name")
85
+ t = _numbers(move.get("time"), "time") # [s]
86
+ data = move.get("set_target_data")
87
+ if not isinstance(data, list) or len(data) != len(t) or len(t) < 2:
88
+ raise ValueError("set_target_data: one sample per time, at least 2")
89
+ if t[0] != 0.0 or t[-1] > MAX_DURATION_S or np.any(np.diff(t) < MIN_STEP_S):
90
+ raise ValueError(f"time: from 0, increasing by {MIN_STEP_S} s at least, up to {MAX_DURATION_S} s")
91
+ key = next(iter(data[0])) if isinstance(data[0], dict) and len(data[0]) == 1 else None
92
+ if key not in ("body", "leg") or not all(isinstance(d, dict) and list(d) == [key] for d in data):
93
+ raise ValueError('set_target_data: every sample {"body": [6]} or every sample {"leg": [3]}')
94
+ size = 6 if key == "body" else 3
95
+ values = np.asarray([_numbers(d[key], key) for d in data if isinstance(d[key], list) and len(d[key]) == size]) # (N, size)
96
+ if len(values) != len(t):
97
+ raise ValueError(f"{key}: {size} values per sample")
98
+ if not np.allclose(values[[0, -1]], 0.0, atol=1e-6):
99
+ raise ValueError(f"{key}: zero at the first and last sample")
100
+ speed = np.abs(np.diff(values, axis=0)) / np.diff(t)[:, None] # per second
101
+ if key == "body":
102
+ if np.abs(values[:, :3]).max() > MAX_SHIFT_M + 1e-9 or np.abs(values[:, 3:]).max() > MAX_TILT_RAD + 1e-9:
103
+ raise ValueError(f"body: beyond {MAX_SHIFT_M} m or {MAX_TILT_RAD} rad")
104
+ if speed[:, :3].max() > MAX_SHIFT_SPEED_MPS or speed[:, 3:].max() > MAX_TILT_SPEED_RAD_S:
105
+ raise ValueError(f"body: faster than {MAX_SHIFT_SPEED_MPS} m/s or {MAX_TILT_SPEED_RAD_S} rad/s")
106
+ else:
107
+ if move.get("default_leg") not in ("tl", "tr"):
108
+ raise ValueError('default_leg: "tl" or "tr" (a front leg)')
109
+ if np.abs(values).max() > MAX_LEG_RAD or speed.max() > MAX_LEG_SPEED_RAD_S:
110
+ raise ValueError(f"leg: beyond {MAX_LEG_RAD} rad or faster than {MAX_LEG_SPEED_RAD_S} rad/s")
111
+
112
+
113
+ def hub_snapshot(repo_id: str) -> Path:
114
+ """Folder of the Hugging Face dataset ``repo_id`` (its JSON files only): downloaded, or the cache when offline."""
115
+ try:
116
+ from huggingface_hub import snapshot_download
117
+ except ImportError as exc:
118
+ raise RuntimeError("moves from the Hub need huggingface_hub: pip install 'chromapi[hub]'") from exc
119
+ kwargs: Dict[str, Any] = {"repo_id": repo_id, "repo_type": "dataset", "allow_patterns": ["*.json"]}
120
+ try:
121
+ return Path(snapshot_download(**kwargs))
122
+ except Exception as exc: # no network, Hub down: the copy downloaded last time
123
+ logger.warning("Moves %s not downloaded (%s): using the cache", repo_id, exc)
124
+ return Path(snapshot_download(**kwargs, local_files_only=True))
125
+
126
+
127
+ def leg_joints(leg: str) -> Tuple[str, str, str]:
128
+ """Coxa, femur and tibia joint names of ``leg``."""
129
+ return (f"{leg}_1", f"{leg}_2", f"{leg}_3")
130
+
131
+
132
+ class _Trajectory:
133
+ """The samples of ``key`` in a move, linearly interpolated (held at both ends)."""
134
+
135
+ def __init__(self, move: Dict[str, Any], key: str) -> None:
136
+ self.description: str = move["description"]
137
+ self._time = np.asarray(move["time"], dtype=float) # [s]
138
+ self._values = np.asarray([sample[key] for sample in move["set_target_data"]], dtype=float) # (N, k)
139
+ self.duration = float(self._time[-1]) # [s]
140
+
141
+ def _at(self, t: float) -> List[float]:
142
+ return [float(np.interp(t, self._time, self._values[:, i])) for i in range(self._values.shape[1])]
143
+
144
+
145
+ class RecordedMove(Move, _Trajectory):
146
+ """The chassis follows the trajectory over the planted feet, then comes back to the start pose."""
147
+
148
+ def __init__(self, move: Dict[str, Any], body: BalanceMove) -> None:
149
+ """``move``: the parsed JSON; ``body``: the BalanceMove that holds the feet."""
150
+ _Trajectory.__init__(self, move, "body")
151
+ self._body = body
152
+ self._elapsed = 0.0 # [s]
153
+ self.done = False
154
+
155
+ def evaluate(self, t: float) -> Pose:
156
+ """Chassis pose at ``t`` [s]."""
157
+ v = self._at(t)
158
+ return (v[0], v[1], v[2]), (v[3], v[4], v[5])
159
+
160
+ def on_start(self) -> None:
161
+ """Restart, from wherever the robot stands."""
162
+ self._elapsed, self.done = 0.0, False
163
+ self._body.on_start()
164
+
165
+ def step(self, state: RobotState, command: MotorCommand, dt: float) -> None:
166
+ """This tick's pose, then the start pose again."""
167
+ self._elapsed += dt
168
+ if self._elapsed < self.duration:
169
+ self._body.set_body_pose(*self.evaluate(self._elapsed))
170
+ else:
171
+ self._body.set_body_pose()
172
+ self.done = self._elapsed >= self.duration + SETTLE_S
173
+ self._body.step(state, command, dt)
174
+
175
+
176
+ class RecordedLegMove(Move, _Trajectory):
177
+ """Shift the weight onto the 3 other feet, play the leg trajectory with ``leg``, put it down, shift back."""
178
+
179
+ def __init__(self, move: Dict[str, Any], body: BalanceMove, leg: str) -> None:
180
+ """``move``: the parsed JSON; ``body``: holds the other 9 joints; ``leg``: the front leg that moves."""
181
+ _Trajectory.__init__(self, move, "leg")
182
+ self._body, self._leg = body, leg
183
+ self._reset()
184
+
185
+ def _reset(self) -> None:
186
+ """Back to the shift phase, nothing measured yet."""
187
+ self._phase = "shift"
188
+ self._elapsed = 0.0 # [s] in the current phase
189
+ self._shift: Optional[np.ndarray] = None # [m] CoM offset, feet frame
190
+ self._start: Optional[List[float]] = None # [rad] leg joints when the trajectory starts
191
+ self.done = False
192
+
193
+ def evaluate(self, t: float) -> Tuple[float, float, float]:
194
+ """Coxa, femur, tibia offsets from the start pose at ``t`` [s] of the trajectory."""
195
+ v = self._at(t)
196
+ return (v[0], v[1], v[2])
197
+
198
+ def on_start(self) -> None:
199
+ """Restart from the shift phase."""
200
+ self._reset()
201
+ self._body.on_start()
202
+
203
+ def _compute_shift(self) -> np.ndarray:
204
+ """CoM offset that puts the centre of mass EMOTE_COM_MARGIN_M inside the support triangle."""
205
+ feet, com = self._body.feet, self._body.com0
206
+ opposite = _DIAGONAL_LEG[self._leg]
207
+ a, b = (feet[leg][:2] for leg in ("tl", "tr", "bl", "br") if leg not in (self._leg, opposite))
208
+ edge = (b - a) / np.linalg.norm(b - a)
209
+ normal = np.array([-edge[1], edge[0]])
210
+ if (feet[opposite][:2] - a) @ normal < 0.0:
211
+ normal = -normal # inward
212
+ shift_xy = max(0.0, EMOTE_COM_MARGIN_M - float((com[:2] - a) @ normal)) * normal
213
+ norm = float(np.linalg.norm(shift_xy))
214
+ if norm > EMOTE_MAX_SHIFT_M:
215
+ shift_xy *= EMOTE_MAX_SHIFT_M / norm
216
+ return np.array([shift_xy[0], shift_xy[1], 0.0])
217
+
218
+ def step(self, state: RobotState, command: MotorCommand, dt: float) -> None:
219
+ """Shift, leg trajectory, land, shift back."""
220
+ if self._shift is None:
221
+ self._body.step(state, command, dt) # anchors the feet
222
+ self._shift = self._compute_shift()
223
+ return
224
+ self._elapsed += dt
225
+ if self._phase == "shift":
226
+ self._body.set_body_pose(_ease(self._elapsed / EMOTE_SHIFT_S) * self._shift)
227
+ if self._elapsed >= EMOTE_SHIFT_S:
228
+ self._phase, self._elapsed = "leg", 0.0
229
+ elif self._phase == "leg":
230
+ joints = leg_joints(self._leg)
231
+ if self._start is None:
232
+ self._start = [command.target_angles[j] for j in joints]
233
+ offsets = (0.0, 0.0, 0.0) if self._elapsed >= self.duration else self.evaluate(self._elapsed)
234
+ self._body.lift(self._leg, {j: q0 + dq for j, q0, dq in zip(joints, self._start, offsets)})
235
+ if self._elapsed >= self.duration:
236
+ self._phase, self._elapsed = "land", 0.0
237
+ elif self._phase == "land":
238
+ self._body.lift(None)
239
+ if self._elapsed >= EMOTE_LAND_S:
240
+ self._phase, self._elapsed = "unshift", 0.0
241
+ elif self._elapsed < EMOTE_SHIFT_S:
242
+ self._body.set_body_pose((1.0 - _ease(self._elapsed / EMOTE_SHIFT_S)) * self._shift)
243
+ else:
244
+ self._body.set_body_pose()
245
+ self.done = True
246
+ self._body.step(state, command, dt)
247
+
248
+
249
+ class RecordedMoves:
250
+ """A library of recorded moves: every valid ``<name>.json`` of a folder or of a Hugging Face dataset."""
251
+
252
+ def __init__(self, source: Union[Path, str] = MOVES_DIR) -> None:
253
+ """Read every move of ``source`` once: a folder, or a dataset id ``"<account>/<name>"`` (see :func:`hub_snapshot`)."""
254
+ directory = Path(source)
255
+ if isinstance(source, str) and not directory.is_dir():
256
+ directory = hub_snapshot(source)
257
+ self._moves: Dict[str, Dict[str, Any]] = {}
258
+ for path in sorted(directory.glob("*.json")):
259
+ try:
260
+ if path.stat().st_size > MAX_FILE_BYTES:
261
+ raise ValueError(f"over {MAX_FILE_BYTES} bytes")
262
+ move = json.loads(path.read_text())
263
+ check_move(move)
264
+ except (OSError, ValueError) as exc: # json.JSONDecodeError is a ValueError
265
+ logger.warning("Move %s left out: %s", path.name, exc)
266
+ continue
267
+ self._moves[path.stem] = move
268
+
269
+ def update(self, other: "RecordedMoves") -> None:
270
+ """Add ``other``'s moves; same name: ``other``'s wins."""
271
+ self._moves = {**self._moves, **other._moves}
272
+
273
+ def is_leg_move(self, name: str) -> bool:
274
+ """Whether ``name`` lifts a leg (greeting, kick) rather than posing the chassis."""
275
+ return "leg" in self._moves[name]["set_target_data"][0]
276
+
277
+ def mood(self, name: str) -> Optional[str]:
278
+ """The mood (ring and sound) the file asks for, if any."""
279
+ return self._moves[name].get("mood")
280
+
281
+ def get(self, name: str, body: BalanceMove, leg: Optional[str] = None) -> Union[RecordedMove, RecordedLegMove]:
282
+ """A fresh player of move ``name``, balanced by ``body``; ``leg`` for a leg move (default: the file's)."""
283
+ move = self._moves[name]
284
+ if self.is_leg_move(name):
285
+ return RecordedLegMove(move, body, leg or move["default_leg"])
286
+ return RecordedMove(move, body)
287
+
288
+ def list_moves(self) -> List[str]:
289
+ """Names of the moves, sorted."""
290
+ return list(self._moves)
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Media module for Chromapi."""