Lumi robot software on the Jetson Thor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 15:19:07 +09:00
co-authored by Claude Opus 5.5
commit 96b01fa12e
177 changed files with 39901 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
# Runtime data measured or recorded on this robot (stays on the Thor)
data/camera_extrinsics*.json
data/calib_samples*/
data/doa_*
data/volume.txt
data/speech_speed.txt
# The owner's licensed songs and everything made from them: never commit
data/songs/mine/
# Rendered by audio/sing_render.py from data/songs/*.json
data/songs/*.wav
# Company passwords and addresses
docs/private/
# Logs, models, builds, environments
logs/
Log/
models/
whisper.cpp/
.venv
.venv-songs
.venv-cover
.env
# Rebuilt by assistant/knowledge.py build
knowledge/index.npz
__pycache__/
*.pyc
# test frames with people in them: local only, never in git
tests/data/scene_carrying_jacket_*
tests/data/scene_white_shirt_*
# Work log, plans and test results: local only
CLAUDE.md
docs/ROADMAP.md
docs/WORK_PLAN.md
docs/13_TO_VERIFY_ON_ROBOT.md
docs/14_VOICE_ASSISTANT.md
docs/15_PICK_AND_PLACE.md
docs/16_FETCH_TASKS.md
docs/17_MISSIONS.md
+256
View File
@@ -0,0 +1,256 @@
# Lumi
Software for our **JAKA Lumi** robot. It runs on the NVIDIA Jetson AGX Thor mounted on the robot and makes Lumi an office assistant: it talks with people in English and Korean, drives where it is told, and picks up and puts back a cup by voice.
**Contents:** [About the robot](#about-the-robot) · [Getting started](#getting-started) · [Hardware](#hardware) · [Folder layout](#folder-layout) · [Run](#run) · [Deploying a change](#deploying-a-change) · [Not in git](#not-in-git-local-on-the-thor) · [Pitfalls](#pitfalls) · [Documentation](#documentation)
---
## About the robot
The JAKA Lumi is a **mobile manipulator**: a robot arm on a body that drives, sold by JAKA as an "embodied AI platform". From the floor up:
- a **mobile base** (AGV) with two drive wheels, a lidar and its own navigation computer: it keeps a map of the office, drives to named places (markers) on it and charges itself on a dock;
- a **lifting column** that raises the upper body, and a **waist** that turns it left and right;
- a **head** that turns and nods, with a camera, a microphone array and a speaker in it;
- a **6-joint arm** (JAKA Mini 2) on the side of the column, with a **Zimmer electric gripper** and long steel fingers made for cups;
- a second camera on the **torso**, looking at the table in front of the arm;
- the **Jetson AGX Thor** computer, which runs everything in this repository: speech recognition, the language model, the voice, camera detection and the control of every part.
Each part has its own controller on the robot's network; this software talks to all of them directly (no ROS, no vendor SDK). Numbers and models: [Hardware](#hardware).
### What Lumi can do
- **Talk in English and Korean.** Wake it by name ("Lumi", "Hi Lumi", "루미야") from anywhere; it finds who called by voice direction and camera and answers in English or Korean. Follow-up questions keep the topic, and it can be interrupted while it speaks.
- **Answer questions**, from its own knowledge and from the internet: date and time, weather, Wikipedia, news.
- **Greet people.** In Greeter mode it greets a person who stops in front of it and asks how it can help.
- **Go to places.** "Come here" brings it to about 1 m in front of the caller; "go to p2", "go home" to a marker on the office map. In Patrol mode it drives its round and stops only for a person in its path. It goes to the charger on low battery.
- **Pick up a cup and put it back.** It finds the cup with the torso camera, plans the grasp, picks it, can drive holding it, and puts it back where it was.
- **Stop on "stop" / "멈춰"**: the base, the arm and its own speech.
---
## Getting started
### 1. Connect to the robot
All of Lumi's parts share one network, the **robot LAN** (`192.168.10.x`). It has no internet; the Thor reaches the internet over its own Wi-Fi to the office network.
- **Wi-Fi**: join the robot's own Wi-Fi `Lumi<serial>` (2.4 GHz) or `Lumi<serial>-5G`; the serial is on the robot's name plate. Password: **ask the robot's owner**.
- **Cable**: plug into the gigabit RJ45 port on the back of the base.
- Your computer must get a `192.168.10.x` address. If it gets `10.5.5.x`, set one by hand as described in [docs/02 §2](docs/02_NETWORK_AND_ACCESS.md).
- Check: `ping 192.168.10.240` (the Thor), then open the dashboard below.
- **SSH to the Thor**: `ssh <user>@192.168.10.240`. User name and password: **ask the robot's owner**.
### 2. Pages and services
| What | Address | For |
|---|---|---|
| **Dashboard** | http://192.168.10.240:8100/view | Everyday use: cameras, map, Greeter / Patrol, STOP |
| **Robot API** (Swagger) | http://192.168.10.240:8100/docs | Every endpoint of this software with "Try it out": status, base, body, arm, gripper, skills, tasks, cameras, assistant |
| API health | http://192.168.10.240:8100/health | `{"ok": true}` while the API runs |
| Camera picture | http://192.168.10.240:8100/camera/torso.jpg (or `head.jpg`) | Latest frame of one camera; `/camera/<name>.mjpg` is a live stream |
| **Cobo π** (arm controller) | https://192.168.10.90 | Arm power, enable, jog, safety settings, tool I/O, programs. Accept the self-signed certificate. Login: **ask the robot's owner** |
| Body page and API | http://192.168.10.90:5000 | Lift, waist, head: enable / disable / reset / stop, joint table; the API is under `/api/extaxis/` ([docs/03](docs/03_BODY_LIFT_WAIST_HEAD.md)) |
| Arm JSON port | `192.168.10.90:10001` (TCP) | The arm controller's command port, used by `robot/arm.py` and `robot/gripper.py` |
| **Base panel** (AGV) | http://192.168.10.10:9001 | Map, markers, no-go lines, manual driving, soft E-stop, battery. Use Chrome. The map builder opens on port 8809 |
| Base API | `192.168.10.10:31001` (TCP) | The base's command port, used by `robot/agv.py` ([docs/05](docs/05_AGV_BASE.md)) |
Used only by the API, on the Thor itself: whisper speech-to-text `:8096`, the embedding server `:8095`, Ollama `:11434`. Other services on the Thor (`:8000`, `:8001`, `:8090`, `:3080`) belong to colleagues.
### 3. Switch Lumi on
Open the dashboard, http://192.168.10.240:8100/view. Both switches are off after every reboot.
- **Greeter**: Lumi stays in place and talks with people. Stand in front of it or call it by name ("Lumi", "Hi Lumi", "루미야"), then ask in English or Korean. A wireless clip mic on the person hears far better than the head microphones at a distance.
- **Patrol**: Lumi also drives and uses the arm: everything that moves.
- **■ STOP** in the top bar stops the base, the arm, the body and the assistant at once.
### 4. Safety
- **Ask before moving anything** (base, lift, waist, head, arm, gripper). People work next to the robot.
- Someone stands at a **stop** while anything new runs: the red **E-stop on the column** (cuts arm power, stops the lift), the dashboard **■ STOP**, or "stop" / "멈춰". The first run of any new arm motion is slow and watched.
- **No hands near the gripper fingers** when it may close: it closes with 90 N or more and cannot be stopped half way.
- The arm sticks out past the base (about 0.44 m from its centre in `look`) and the base's navigation does not know it: keep the arm's sweep and the base's path clear. The lidar does not see glass or low, black or shiny things.
- **Never restart the API or the assistant while the base drives**: check `curl -s localhost:8100/status` → `base.move_status` first. Stopping the assistant cancels the drive.
- Do not change controller, base or network settings without the owner (the arm's mounting in Cobo π must stay as it is: the arm is side-mounted). The arm's collision limits are still the loose defaults: no arm work close to people.
- Do not push the base while it is on; do not drive with the manual charging cable plugged in.
Full rules: [docs/11_SAFETY.md](docs/11_SAFETY.md).
### 5. For developers
The code runs on the Thor (it needs the robot's hardware); the self-checks also run on any Linux machine with the venv. Repository URL and access: ask the robot's owner.
```bash
git clone <repo-url> ~/Dev/lumi-wave
cd ~/Dev/lumi-wave
# Python 3.12 venv, with this folder on its path (modules import each other by folder)
uv venv --python 3.12 .venv
uv pip install --python .venv numpy opencv-python-headless pyorbbecsdk2 fastapi uvicorn supertonic soundfile
uv pip install --python .venv tensorrt-cu13 cuda-python # GPU detection, on the Thor
echo "$PWD" > .venv/lib/python3.12/site-packages/lumi_wave.pth
for t in tests/test_*.py; do .venv/bin/python $t || echo "FAILED: $t"; done # self-checks, nothing moves
systemctl --user restart lumi-api # after a change; check the base is not driving first
tail -f logs/api.log logs/lumi.log # robot log, assistant log
```
Models, whisper.cpp and calibration files are local to the Thor: [Not in git](#not-in-git-local-on-the-thor). What to restart after a change: [Deploying a change](#deploying-a-change).
---
## Hardware
Lumi is 510 × 510 mm on the floor, 1460–1860 mm tall (with the lift), 95.6 kg, with 12 degrees of freedom: 2 drive wheels, lift, waist, head yaw and pitch, 6 arm joints. Full specifications and sources: [docs/01_HARDWARE.md](docs/01_HARDWARE.md).
| Part | What it is | Key facts | How we reach it | Doc |
|---|---|---|---|---|
| **Base (AGV)** | Differential-drive base with its own navigation computer, lidar SLAM | 2 × 160 W hub motors; 0.6 m/s default, 1.2 m/s max (joystick command ±0.5 m/s, ±1.0 rad/s); turning radius 307 mm; needs a 700 mm passage. 24 V 45 Ah Li-ion, about 10 h; contact charging on a dock | TCP API of the base, over the robot LAN | [05](docs/05_AGV_BASE.md) |
| Base sensors | Used by the base's own navigation | 2D lidar 0.02–10 m, 240°, 30 Hz; front 3D camera 0.35–2 m; 5 ultrasonic sensors 0.03–0.55 m; 6-axis IMU; infrared; bumper. The lidar does not see glass | Base API (map, distance probe) | [05](docs/05_AGV_BASE.md) |
| **Body** | Lifting column, waist turn, head yaw, head pitch | Lift 0–400 mm in hardware, 0–300 mm in the API; **our code holds it at 0–105 mm** (the head camera's cable is too short). Waist ±160° hardware, ±140° API. Head yaw ±180° (about 6 s per 90°), pitch −5…+35° | HTTP API on the arm controller | [03](docs/03_BODY_LIFT_WAIST_HEAD.md) |
| **Arm** | JAKA Mini 2, 6 joints, mounted on the side of the column | Payload 2 kg, reach 580 mm, repeatability ±0.1 mm, 9.9 kg, max tool speed 1 m/s, 48 V. Controller (MiniCab) inside the base, web UI Cobo π. In the `look` pose the hand is ~0.44 m from the base centre, past the base edge | JSON port of the arm controller | [04](docs/04_ARM.md) |
| **Gripper** | Zimmer GEP2013IO-05-B electric parallel gripper with long steel cup fingers | 13 mm stroke per jaw, 90–360 N in four levels (set to level 1), ~0.54 kg, ~1 s per stroke. Inner gap open → closed: tips 88 → 59 mm, round hook 96 → 70 mm. Software grips 61–92 mm wide objects | Arm tool I/O (all PNP): DO_1 close, DO_2 open (never both), AI_1 finger position, DI_1 optical sensor looking below the gripper | [10](docs/10_GRIPPER.md), [gripper/](docs/gripper/README.md) |
| **Head camera** | Orbbec Gemini 2 L RGB-D, front of the head | Colour used at 1280 × 720, depth 0.02–10 m (brochure 0.2–10 m), colour FoV 94° × 68°. Turns with the head; watches people while Lumi stands. Calibrated to the arm at any head pose: median 6.0 mm | USB 3, through a USB 3 hub in the head shared with the microphones and speaker | [06](docs/06_CAMERAS_AND_VISION.md) |
| **Torso camera** | Orbbec Gemini 2 L RGB-D, under the handle on the column | Same link as the arm base, so its calibration holds at any lift and waist angle: median 3.3 mm. Sees objects for picking, the table, the path while driving | USB 3 | [06](docs/06_CAMERAS_AND_VISION.md) |
| **Microphones** | iFlytek AIUI XF-USB-MC ring array in the head; optional DJI Mic Mini wireless clip mic | Array: 8 channels at 16 kHz (6 mics), SNR > 70 dB, 3–5 m. Voice direction is computed by our code (SRP-PHAT). The clip mic is used automatically when its receiver is plugged in and hears 5–10× better at 4–5 m | USB audio | [07](docs/07_VOICE_AND_AUDIO.md) |
| **Speaker** | USB speaker in the head ("USB Audio Device") | Volume 55 % in the office; set from the dashboard or by voice | USB audio | [07](docs/07_VOICE_AND_AUDIO.md) |
| **Computer** | NVIDIA Jetson AGX Thor Developer Kit | Blackwell GPU, 2070 TOPS (INT8) by spec; measured 14 CPU cores and 122 GB memory shared by CPU and GPU; JetPack R38.4, CUDA 13.0. Runs the LLM, speech, detection and all control | Ethernet to the robot LAN; its own Wi-Fi for the internet (the robot LAN has none) | [08](docs/08_NVIDIA_THOR.md) |
Safety: E-stop buttons on the column and in the base; the arm's collision limits in Cobo π are still the factory defaults. Read [docs/11_SAFETY.md](docs/11_SAFETY.md) before moving anything.
---
## Folder layout
```
lumi-wave/ run with the venv: .venv/bin/python <folder>/<module>.py
├── api/ robot API (FastAPI :8100, Swagger /docs) and the dashboard (/view)
├── assistant/ the voice assistant: main loop (lumi.py), answers (brain.py), knowledge, web lookups
├── audio/ microphones, speech to text, text to speech, voice direction
├── vision/ camera service (the only camera owner), detection, objects in mm, calibration
├── robot/ one driver per piece of hardware: base, body, arm, gripper; checked arm motion
├── manipulation/ pick and place skills
├── tasks/ whole jobs made of skills, driving and talking
├── tests/ self-checks without the robot
├── data/ taught and calibrated values
├── knowledge/ texts Lumi answers from
├── logs/ every log file and debug picture
├── docs/, tools/ documentation; scripts run from a laptop
└── lumi-api.service starts the API at boot (systemd user service)
```
Modules import each other by folder (`from robot import arm`, `from vision import camview`). The venv has `lumi_wave.pth` in its `site-packages` with the path of this folder, so any module runs directly from any directory: `.venv/bin/python robot/gripper.py`.
---
## Run
Always with the venv (the system Python has no OpenCV):
```bash
cd ~/Dev/lumi-wave
.venv/bin/python api/server.py # normally started at boot
.venv/bin/python assistant/lumi.py # assistant in the terminal (switch the dashboard's Greeter/Patrol off first)
.venv/bin/python assistant/lumi.py --no-camera --no-drive
.venv/bin/python assistant/brain.py --act # type questions, see answers and actions
.venv/bin/python audio/ears.py # speak, see the text
.venv/bin/python audio/mouth.py "Hello" # Lumi says it
.venv/bin/python robot/gripper.py # gripper state
.venv/bin/python robot/motion.py # joints, TCP, named poses
.venv/bin/python vision/objects.py --watch # what the torso camera sees, in mm
.venv/bin/python manipulation/skills.py plan cup # dry run of a pick and place (nothing moves)
.venv/bin/python assistant/web.py weather Seoul
.venv/bin/python assistant/knowledge.py build # after changing knowledge/
.venv/bin/python vision/camview.py --stop # free the cameras for camera_test / camera_fps
```
At boot the user service `lumi-api` ([lumi-api.service](lumi-api.service), installed in `~/.config/systemd/user/`, linger on, so no login is needed) starts `api/server.py` 20 s after boot and restarts it 5 s after it dies. Restarting the API does not stop the camera service, whisper or a running assistant. The assistant runs only while Greeter or Patrol is switched on in the dashboard; both are off after a reboot on purpose.
```bash
systemctl --user status lumi-api # running? since when?
systemctl --user restart lumi-api # after changing api/, robot/, manipulation/ or tasks/
systemctl --user stop lumi-api # stays stopped until start or the next boot
```
Logs are in `logs/`: `lumi.log` (assistant), `lumi_console.log` (its stderr), `api.log`, `camview.log`, `whisper_server.log`, `embed_server.log`. The dashboard's Settings → Logs shows the robot log or the assistant log, latest errors on top.
---
## Deploying a change
1. Check that the robot is not driving: `curl -s localhost:8100/status` → `base.move_status` must not be `running`. **Restarting the assistant cancels a drive in progress.**
2. Edit, then `.venv/bin/python -m py_compile <file>`.
3. Restart what uses the file:
- `assistant/`, `audio/` → switch Greeter/Patrol off and on in the dashboard (the API restarts the assistant);
- `api/` → `systemctl --user restart lumi-api`;
- `vision/camview.py`, `person.py`, `objects.py` → `vision/camview.py --stop`, then `--serve`;
- `robot/`, `manipulation/`, `tasks/` are used by all of them: restart the API, and the assistant if it runs.
4. Watch `logs/lumi.log` / Settings → Logs.
---
## Not in git (local on the Thor)
| Path | What | How it is made |
|---|---|---|
| `logs/` | all log files and debug pictures | written at run time |
| `data/camera_extrinsics*.json`, `data/calib_samples*/`, `data/doa_*`, `data/volume.txt`, `data/speech_speed.txt` | calibrations and settings of this robot | `vision/calib.py`, `audio/doa.py`, the dashboard |
| `.venv/` | Python 3.12 venv with `site-packages/lumi_wave.pth` (the path of this folder): numpy, opencv-python-headless, pyorbbecsdk2, fastapi, uvicorn, supertonic, soundfile, tensorrt-cu13, cuda-python | |
| `models/yolov8s.onnx`, `models/yolov8s.engine` | GPU detector. The engine only runs on the TensorRT version and GPU it was built with: rebuild after a JetPack or TensorRT change | `YOLO("yolov8s.pt").export(format="onnx", imgsz=640, opset=17)`; `vision/yolo_engine.py models/yolov8s.onnx models/yolov8s.engine` (~100 s) |
| `models/yolov8n.onnx` | CPU fallback detector | `YOLO("yolov8n.pt").export(format="onnx", imgsz=640, opset=12, simplify=True)` |
| `models/yolo11s-pose.onnx`, `.engine` | pose keypoints for `vision/pose.py` | ultralytics export, then `vision/yolo_engine.py` |
| `models/face_detection_yunet_2023mar.onnx`, `models/face_recognition_sface_2021dec.onnx` | face detector and embedding for `vision/reid.py` (without them only clothes are used) | github.com/opencv/opencv_zoo |
| `models/ggml-large-v3-turbo-q5_0.bin` | whisper model | Hugging Face `ggerganov/whisper.cpp` |
| `models/supertonic3/` | TTS model | Hugging Face `Supertone/supertonic-3` |
| `whisper.cpp/` | v1.9.5, built with CUDA | `cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=110 -DCMAKE_BUILD_TYPE=Release && cmake --build build -j 12 --target whisper-server whisper-cli` |
| `~/models/bge-m3-Q8_0.gguf` | embedding model for the knowledge base | Hugging Face |
| `knowledge/index.npz` | knowledge vectors | `assistant/knowledge.py build` |
| Ollama `gemma4:26b` | LLM | `ollama pull gemma4:26b` |
| `docs/private/` | company-internal notes (access, vendor manuals, screenshots) | kept off git |
The Orbbec cameras need the udev rule `SUBSYSTEM=="usb", ATTR{idVendor}=="2bc5", MODE="0666"` in `/etc/udev/rules.d/99-orbbec.rules`.
---
## Pitfalls
- **Never open the cameras from a second program** while the camera service runs. After `vision/camview.py --stop` / `--start` the torso camera may not be found for a few seconds while it re-enumerates: wait and start again.
- **Check the USB speed after any cable work** (`/sys/bus/usb/devices/*/speed` must say 5000 for the cameras). A head camera opened at USB 2 stays colour-only until the camera service is restarted.
- **Never call `tasks/fetch.py` functions from a second process while the API runs**: its log writes that process's empty state over `/dev/shm/lumi_task.json`, and the held object is forgotten.
- After a controller power cycle the body axes are disabled and every move times out; `robot/head.py` enables them. All tool I/O must be PNP in Cobo π, or the gripper does not move.
- The base drives into a table's margin and reports "succeeded" without moving; the last part of a reach is a straight checked drive. Drives with the arm in `carry` stall (the base's 3D camera sees the hand): drive in `look`.
- The base's planning API does not check real paths, so `robot/nav.py` uses the map image. Closed glass doors need a no-go line in the base's web panel.
- The body API's `/stop` does not stop a `moveto`, so hold-to-move uses small steps.
- `pkill -f` / `pgrep -f` also match your own shell's command line: find the PID with `ps -eo pid,args | grep "[n]ame"` and kill that.
- Headless Chrome screenshots of the dashboard: do not use `--timeout` (it freezes the page's JavaScript).
- Other projects and services on this Thor belong to colleagues (`~/Dev/lumi_edu`, `lumi-vision`, `lumi_voice_app`, services on :8000, :8001, :8090, :3080). Do not touch them.
Every value meant to be tuned by hand, with its file: [docs/TUNING.md](docs/TUNING.md).
---
## Documentation
| Document | Content |
|---|---|
| [00 Start here](docs/00_START_HERE.md) | From zero to developing on the robot: install, power on, connect, first tests |
| [01 Hardware](docs/01_HARDWARE.md) | Every specification, connectors, lights, model files |
| [02 Network and access](docs/02_NETWORK_AND_ACCESS.md) | Connecting a computer; web pages, apps |
| [03 Body: lift, waist, head](docs/03_BODY_LIFT_WAIST_HEAD.md) | The four body joints, their API and ranges |
| [04 Arm](docs/04_ARM.md) | Cobo π, SDK, units, settings, tool connector |
| [05 Mobile base](docs/05_AGV_BASE.md) | Mapping, markers, driving, navigation API |
| [06 Cameras and vision](docs/06_CAMERAS_AND_VISION.md) | Orbbec cameras, intrinsics, calibration, scene understanding |
| [07 Voice and audio](docs/07_VOICE_AND_AUDIO.md) | Microphone array, speaker, voice direction |
| [08 Jetson Thor](docs/08_NVIDIA_THOR.md) | The AI computer, setup, what runs on its GPU |
| [09 ROS 2, teleop, simulators](docs/09_ROS2_TELEOP_AND_SIM.md) | Vendor ROS 2, MoveIt 2, Isaac Sim, VR teleoperation |
| [10 Gripper](docs/10_GRIPPER.md) | The Zimmer gripper: signals, PNP, measurements |
| [Gripper fingers](docs/gripper/README.md) | Finger shape and measured gaps, photos |
| [11 Safety](docs/11_SAFETY.md) | Stop buttons and rules; read before any motion |
| [12 Sources](docs/12_SOURCES.md) | Where each fact came from; downloads |
| [Tuning](docs/TUNING.md) | Speeds, distances, thresholds with their file |
| [docs/README.md](docs/README.md) | Index of the reference docs |
Company-internal notes (access, vendor manuals, screenshots) are kept off git.
View File
+120
View File
@@ -0,0 +1,120 @@
"""Hold-to-move ("jog") control for the dashboard: base, head, waist, lift and arm joints.
The page sends POST /jog about every 150 ms while a button is held; each call keeps that axis moving
for HOLD_S more. When the calls stop (button released, page closed, network gone) the axis stops by
itself within one small step. Nothing here runs a long motion that has to be cancelled:
- base: /api/joy_control, each command lasts 0.5 s on the AGV anyway
- head / waist / lift: short moveto steps (the body /stop call does not stop a moveto)
- arm: short relative joint_move steps over TCP 10001
"""
import threading
import time
from robot import agv
from robot import arm
from robot import head
HOLD_S = 0.35 # s an axis keeps moving after the last /jog call
# axis: (index in the body status, step per move, low limit, high limit)
BODY_AXES = {"lift": (0, 10.0, 0.0, head.LIFT_MAX_MM), "waist": (1, 3.0, -90.0, 90.0),
"head_yaw": (2, 3.0, -180.0, 180.0), "head_pitch": (3, 2.0, -5.0, 35.0)}
ARM_AXES = {f"j{i}": i - 1 for i in range(1, 7)}
ARM_STEP = 2.0 # deg per step
ARM_SPEED = 20.0 # deg/s at speed 100 %
BASE_V = 0.3 # m/s at speed 100 %
BASE_W = 0.6 # rad/s at speed 100 %
class Jogger:
def __init__(self):
self.lock = threading.Lock()
self.cmd = {} # axis -> (direction, speed 0..1, deadline)
self.threads = {}
self.last_error = None
def hold(self, axis, direction, speed=0.5):
if axis not in BODY_AXES and axis not in ARM_AXES and axis not in ("base_drive", "base_turn"):
raise ValueError(f"unknown axis {axis}")
group = "base" if axis.startswith("base") else "arm" if axis in ARM_AXES else "body"
with self.lock:
if group == "base": # drive and turn may be held together
self.cmd = {a: c for a, c in self.cmd.items() if a.startswith("base")}
else: # one body / arm axis at a time
self.cmd = {a: c for a, c in self.cmd.items() if not (a in BODY_AXES or a in ARM_AXES)}
self.cmd[axis] = (1 if direction > 0 else -1, max(0.05, min(1.0, speed)), time.time() + HOLD_S)
t = self.threads.get(group)
if t is None or not t.is_alive():
t = threading.Thread(target=getattr(self, f"_run_{group}"), daemon=True)
self.threads[group] = t
t.start()
def stop(self):
with self.lock:
self.cmd = {}
try:
agv.request("/api/joy_control?linear_velocity=0&angular_velocity=0")
except Exception:
pass
def _active(self, axes):
now = time.time()
with self.lock:
return {a: c for a, c in self.cmd.items() if a in axes and c[2] > now}
def _run_base(self):
while True:
active = self._active(("base_drive", "base_turn"))
if not active:
return
v = active.get("base_drive", (0, 0, 0))
w = active.get("base_turn", (0, 0, 0))
try:
agv.request(f"/api/joy_control?linear_velocity={v[0] * v[1] * BASE_V:.3f}"
f"&angular_velocity={w[0] * w[1] * BASE_W:.3f}", timeout=1.0)
except Exception as e:
self.last_error = f"base: {e}"
time.sleep(0.1)
def _run_body(self):
while True:
active = self._active(BODY_AXES)
if not active:
return
axis, (direction, speed, _) = next(iter(active.items()))
index, step, low, high = BODY_AXES[axis]
try:
pos = head.status()
target = max(low, min(high, pos[index] + direction * step))
if abs(target - pos[index]) < 0.05: # at the limit
time.sleep(0.1)
continue
pos[index] = target
head.moveto(pos, 20 + 60 * speed, 60, timeout=10)
except Exception as e:
self.last_error = f"{axis}: {e}"
time.sleep(0.3)
def _run_arm(self):
while True:
active = self._active(ARM_AXES)
if not active:
return
axis, (direction, speed, _) = next(iter(active.items()))
delta = [0.0] * 6
delta[ARM_AXES[axis]] = direction * ARM_STEP
deg_s = ARM_SPEED * speed
try:
r = arm.cmd("joint_move", relFlag=1, jointPosition=delta, speed=deg_s, accel=deg_s * 3)
if r.get("errorCode") != "0":
self.last_error = f"{axis}: {r.get('errorMsg') or r}"
time.sleep(0.3)
continue
except Exception as e:
self.last_error = f"{axis}: {e}"
time.sleep(0.3)
continue
time.sleep(ARM_STEP / deg_s + 0.05) # let this step finish before the next
jogger = Jogger()
+1074
View File
File diff suppressed because it is too large Load Diff
+1295
View File
File diff suppressed because it is too large Load Diff
View File
+68
View File
@@ -0,0 +1,68 @@
""""What can you do?" / "뭐 할 수 있어?": a fixed short overview of what Lumi can do, the rest on "tell me more".
The language model left out half of it (2026-10-21: "I can chat, tell the time and weather, drive to places on my
map, and pick up and bring cups"), so these words are answered here. Keep the lines in step with
knowledge/lumi_about_en.md "What I can do now" and brain.SYSTEM "What you can do".
python assistant/abilities.py "what can you do?"
"""
import re
import sys
ASKED = re.compile(r"\bwhat (?:else |all |things |kinds? of things )?(?:can|could) you do\b(?!\s+(?:with|about|if|when|to|for (?:it|that)))|"
r"\bwhat (?:are|r) (?:all )?your (?:abilities|skills|capabilities|functions|features|talents)\b|"
r"\bwhat are you (?:able to do|capable of|good at)\b|\bwhat do you do\b(?!\s+(?:with|when|if|for fun))|"
r"\bwhat can you help (?:me |us )?with\b|\btell me (?:about )?(?:what you can do|your (?:abilities|skills))\b|"
r"\b(?:list|show me) (?:your|what you can) (?:abilities|skills|do)\b|^\W*(?:your )?(?:abilities|skills)\W*$|"
r"(?<![가-힣]로 )(?<![가-힣]으로 )(?:뭐|뭘|무엇|무엇을|뭐를)\s*(?:또\s*)?할\s*(?:수|줄)\s*(?:있|알)|"
r"무슨\s*일을?\s*(?:해|하|할)|어떤\s*(?:일|것|거|걸)을?\s*(?:할\s*수|해|하)|할\s*수\s*있는\s*(?:게|것|거|일)|"
r"뭐\s*하는\s*로봇|무슨\s*기능|어떤\s*기능|기능\S*\s*(?:뭐|뭔|있|알려)|(?:능력|기능)\S*\s*(?:뭐|뭔|알려|소개)", re.I)
MORE = re.compile(r"^\W*(?:(?:yes|yeah|yep|sure|ok|okay|please|lumi|and)\W*)*(?:tell me more|more|go on|what else|and\?|"
r"and what else|anything else|details?|yes|yeah|yep|sure|ok|okay|please)(?:\W+(?:please|lumi))*\W*$|"
r"\bwhat else can you do\b|\btell me (?:more|everything|the rest)\b|"
r"^\W*(?:네|예|응|어|그래요?|좋아요?|좋아)?\W*(?:더|자세히|전부|다)?\s*(?:알려|말해|얘기해|들려)\s*(?:줘|주세요|줄래요?|봐)?\W*$|"
r"^\W*(?:네|예|응|그래요?|좋아요?|좋아|그리고요?|또요?|또\s*뭐\S*|그\s*외에는?\S*|더\s*있어요?|더요)\W*$|또\s*뭐\s*할\s*수", re.I)
SHORT_MARK = "ACTION: none abilities" # the history line of the short overview (lumi.fixed_answer)
SHORT = {"en": "I can talk with you and answer your questions, also from the internet, and I can look at what's "
"around me and understand it. I can pick things up and bring them to you, go to places, follow you, "
"wave and even sing. Shall I tell you more?",
"ko": "저는 대화하면서 궁금한 걸 답해 드리고, 인터넷에서 찾아볼 수도 있어요. 주변을 보고 무엇이 있는지 이해할 수 있고, "
"물건을 집어서 가져다드리거나, 여러 곳에 가고, 따라가고, 손을 흔들고 노래도 불러요. 더 알려 드릴까요?"}
LONG = {"en": "I talk with you in English and Korean, and when I don't know something I look it up on the internet. "
"I can look at what's around me and understand it: objects, people, what you're wearing or holding. "
"I can pick things up, bring them to you or take them somewhere else and put them down, or take "
"something from your hand. I go to the places on my map, move or turn as far and as fast as you say, "
"and follow you when you say \"follow me\". And I like to wave and sing songs, like Arirang, Happy "
"Birthday or Fantastic Baby.",
"ko": "영어와 한국어로 대화하고, 모르는 건 인터넷에서 찾아봐요. 주변을 보고 무엇이 있는지 이해할 수 있어요. 물건이나 "
"사람, 입고 계신 옷이나 손에 든 것도요. 물건을 집어서 가져다드리거나 다른 곳에 옮겨 내려놓고, 손에 든 걸 받아 "
"드릴 수도 있어요. 지도에 있는 장소로 가고, 말씀하시는 거리와 속도로 움직이거나 돌고, \"따라와\"라고 하시면 "
"따라가요. 그리고 손을 흔들거나 아리랑, 생일 축하 노래, 판타스틱 베이비 같은 노래도 불러 드려요."}
def asked(text):
"""Do these words ask what Lumi can do? ("what can you do?", "what are your abilities", "넌 무슨 일을 해?")"""
return bool(ASKED.search(text or ""))
def more_asked(text, last=""):
""""Tell me more", "what else?", "yes", "더 알려 줘" right after the short overview (`last` = the answer just before,
from brain history), or "what else can you do?" at any time."""
t = text or ""
if re.search(r"\b(?:what else can you do)\b|또\s*뭐\s*할\s*수", t, re.I):
return True
return (last or "").startswith(SHORT_MARK) and bool(MORE.search(t))
def answer(text, lang="en", last=""):
"""("short" | "long", what to say) for an ability question or its follow-up, else None."""
if more_asked(text, last):
return "long", LONG[lang]
if asked(text):
return "short", SHORT[lang]
return None
if __name__ == "__main__":
print(answer(" ".join(sys.argv[1:])))
+1615
View File
File diff suppressed because it is too large Load Diff
+357
View File
@@ -0,0 +1,357 @@
"""Example exchanges about Cutshion Company and its robots, in the format of assistant/talk_examples.py.
EXAMPLES = [(category, lang, said, reply)]; talk_examples.pick(said, lang, k, bank=...) picks the closest ones.
Facts come only from knowledge/cutshion_en.md (taken from cutshion.com). The basic company question gets one short
answer and an offer to say more; details only when asked; what the site does not say is "I don't have that
information". When the visitor changes the topic, the reply answers the new topic and leaves the company alone.
Korean replies are always polite (-요 / -습니다), whatever level the visitor speaks.
python assistant/company_examples.py # self-check
python assistant/company_examples.py "what is cutshion"
"""
import re
import sys
_BANK = {
"company_basic": {
"en": [
("What is Cutshion?", "Cutshion is a Korean robot company, founded in 2022, that makes robot applications like barista, AI drawing and cooking robots. It's based in Seoul. What would you like to know more about?"),
("Tell me about your company.", "Cutshion is a robot company from Seoul, founded in 2022. It makes robot apps such as barista, drawing, cooking and ice cream robots. Anything you'd like to hear more about?"),
("What kind of company is Cutshion?", "It's a Korean robot company that builds robot applications, for example a barista robot and an AI drawing robot. It's based in Seoul. What would you like to know?"),
("What does Cutshion do?", "Cutshion makes robots do real jobs: it builds robot apps like barista, cooking, drawing and welding robots, plus AI vision and a robot platform. Shall I tell you about one of them?"),
("Who is Cutshion?", "Cutshion is the Seoul robot company that developed me. It makes robot applications such as barista and drawing robots. What would you like to know about it?"),
("Can you tell me about Cutshion?", "Sure. Cutshion is a Korean robot company, started in 2022, making robots for cafes, kitchens, factories, events and schools. Which part interests you?"),
("What's Cutshion?", "A Korean robot company that makes robot applications, like a barista robot and an AI drawing robot. Its head office is in Seoul. Want to hear more about something?"),
("Introduce your company, please.", "Gladly. Cutshion, founded in 2022 in Seoul, makes robot applications such as barista, cooking, ice cream and drawing robots. What would you like to know more about?"),
("Who made you?", "Cutshion Company developed me. Would you like to hear what else Cutshion makes?"),
("Which company built you?", "I was developed by Cutshion, a robot company in Seoul. Anything you'd like to know about it?"),
("What company is behind you?", "Cutshion is. It's a Korean company that makes robot applications. Would you like to know more?"),
("What's the company you work for?", "I work for Cutshion, a robot company from Seoul that makes robot apps like barista and drawing robots. What else would you like to know?"),
("Is Cutshion a big company?", "I don't have information about its size. I can tell you that it's a Korean robot company founded in 2022. What would you like to know about it?"),
("What's Cutshion's main business?", "Robot applications: software and complete robot solutions, like the barista robot, cooking robot and AI drawing robot. Which one should I tell you about?"),
("So what is this company about?", "Cutshion is about robot apps: robots that make coffee, cook, draw portraits, weld and more. Where should I start?"),
("Give me a quick overview of Cutshion.", "Quick version: a Seoul robot company since 2022, making barista, drawing, cooking and other robot apps. You can reach it at cutshion@cutshion.com. What else would you like to know?"),
("What is Cutshion's mission?", "To be the best robot application provider: not just selling robots, but creating robot apps and an ecosystem for them. Would you like an example?"),
("What is Cutshion's slogan?", "Its slogan is \"Soft & Flexible Idea\". Anything else about Cutshion?"),
("Is Cutshion a Korean company?", "Yes, Cutshion is a Korean robot company with its head office in Seoul. Would you like to know more?"),
("When was Cutshion founded?", "Cutshion was founded as a company in July 2022."),
("Who is the CEO of Cutshion?", "The CEO is Lee Min-seok."),
("Who founded Cutshion?", "Cutshion was founded by its CEO, Lee Min-seok, in 2022. It's his third company."),
("Is Cutshion a startup?", "Yes, it's a young company, founded in 2022, and certified as a venture business in 2023."),
("Cutshion, what's that?", "That's the company that developed me: a Korean robot company making robot apps, like a coffee-making barista robot. What would you like to know?"),
("Explain Cutshion in one sentence.", "Cutshion is a Seoul robot company that makes robots useful through robot applications, from coffee to welding."),
("I've never heard of Cutshion.", "It's a young Korean robot company, founded in 2022, making barista, drawing and cooking robots, among others. Shall I tell you more?"),
("What's your company's name?", "My company is Cutshion. Would you like to hear what it does?"),
("Tell me about Cutshion Company.", "Cutshion is a Korean robot application company, founded in 2022 and based in Seoul. You can contact it at 070-8959-2960. What else would you like to know?"),
],
"ko": [
("쿳션은 뭐 하는 회사야?", "쿳션은 2022년에 설립된 한국 로봇 회사로, 바리스타 로봇이나 AI 드로잉 로봇 같은 로봇 애플리케이션을 만들어요. 본사는 서울에 있어요. 더 궁금하신 점이 있으세요?"),
("쿳션은 무슨 회사예요?", "쿳션은 서울에 있는 로봇 회사예요. 바리스타, 드로잉, 조리, 아이스크림 로봇 같은 로봇 앱을 만들어요. 더 궁금하신 점이 있으세요?"),
("쿳션은 어떤 회사입니까?", "쿳션은 2022년에 설립된 로봇 애플리케이션 회사입니다. 바리스타 로봇, AI 드로잉 로봇 등을 만들고 본사는 서울에 있습니다. 더 알고 싶으신 게 있으세요?"),
("회사 소개 좀 해줘.", "네, 쿳션은 로봇이 카페, 주방, 공장, 행사장에서 일할 수 있게 로봇 앱을 만드는 한국 회사예요. 어떤 부분이 궁금하세요?"),
("회사 소개해 주세요.", "쿳션은 2022년 서울에서 시작한 로봇 회사예요. 바리스타 로봇, 조리 로봇, 드로잉 로봇 같은 로봇 앱을 만들어요. 더 궁금하신 점이 있으세요?"),
("회사에 대해 설명해 주십시오.", "쿳션은 로봇 애플리케이션을 만드는 한국 로봇 회사입니다. 연락은 070-8959-2960이나 cutshion@cutshion.com으로 하실 수 있습니다. 어떤 점이 더 궁금하세요?"),
("너 누가 만들었어?", "저는 쿳션에서 개발했어요. 쿳션이 만드는 다른 로봇도 소개해 드릴까요?"),
("어느 회사에서 만들었어요?", "쿳션이라는 서울의 로봇 회사에서 만들었어요. 회사에 대해 더 궁금하신 점이 있으세요?"),
("누가 만들었습니까?", "쿳션에서 개발했습니다. 쿳션에 대해 더 알려 드릴까요?"),
("쿳션이 뭐야?", "쿳션은 바리스타 로봇, AI 드로잉 로봇 같은 로봇 앱을 만드는 한국 로봇 회사예요. 더 궁금하신 게 있으세요?"),
("쿳션이 뭐예요?", "서울에 본사가 있는 로봇 회사예요. 2022년에 설립됐고 여러 로봇 애플리케이션을 만들어요. 어떤 게 더 궁금하세요?"),
("이 회사는 뭘 해요?", "로봇이 커피를 만들고, 요리하고, 그림을 그리고, 용접도 하도록 로봇 앱을 만들어요. 하나 골라서 설명해 드릴까요?"),
("쿳션 주력 사업이 뭐야?", "로봇 애플리케이션이에요. 바리스타 로봇, 조리 로봇, AI 드로잉 로봇 같은 거예요. 어떤 걸 소개해 드릴까요?"),
("쿳션 슬로건이 뭐예요?", "슬로건은 'Soft & Flexible Idea'예요. 더 궁금하신 점이 있으세요?"),
("쿳션은 한국 회사예요?", "네, 쿳션은 서울에 본사가 있는 한국 로봇 회사예요."),
("쿳션은 언제 설립됐어요?", "쿳션은 2022년 7월에 법인을 설립했어요."),
("회사 언제 생겼어?", "2022년 7월에 설립됐어요."),
("대표님이 누구예요?", "쿳션 대표이사는 이민석 대표님이에요."),
("창업자가 누구야?", "이민석 대표님이 2022년에 세운 회사예요. 대표님의 세 번째 창업이라고 해요."),
("쿳션 대표이사는 누구입니까?", "이민석 대표님입니다."),
("쿳션? 그게 뭔데?", "저를 만든 회사예요. 바리스타 로봇 같은 로봇 앱을 만드는 한국 로봇 회사예요. 더 궁금하신 점이 있으세요?"),
("쿳션 처음 들어 봐요.", "2022년에 설립된 젊은 한국 로봇 회사예요. 바리스타, 드로잉, 조리 로봇 등을 만들어요. 더 알려 드릴까요?"),
("회사 이름이 뭐예요?", "제 회사는 쿳션이에요. 어떤 일을 하는지 알려 드릴까요?"),
("쿳션 컴퍼니에 대해 알려 주십시오.", "쿳션은 서울에 있는 로봇 애플리케이션 회사로 2022년에 설립됐습니다. 070-8959-2960으로 연락하실 수 있습니다. 더 궁금하신 점이 있으세요?"),
],
},
"products": {
"en": [
("What robots does Cutshion make?", "Barista, AI drawing, cooking, ice cream, candy ball, welding, palletizing and educational robots. Which one would you like to hear about?"),
("What products do you have?", "Robot apps like the barista robot and AI drawing robot, plus AI vision, a robot platform and robot hardware. Shall I explain one?"),
("Tell me about the barista robot.", "It runs a real espresso machine and does the barista's main steps itself: grinding, dosing, tamping and extracting. The coffee tastes the same every time."),
("What does the barista robot do?", "It makes espresso fully automatically, from grinding the beans to extraction, and works alongside human baristas."),
("Can your company's robot make coffee?", "Yes, Cutshion's barista robot makes espresso coffee on a real espresso machine."),
("Who uses the barista robot?", "Cutshion signed a yearly supply agreement with Mega Coffee, and a contract for 200 barista robots in the USA was reported in 2026."),
("Does the barista robot replace baristas?", "It takes over the repeated steps and works together with human baristas, so they have less heavy routine work."),
("Tell me about the drawing robot.", "The AI drawing robot takes your photo, AI turns it into a line drawing, and the robot arm draws it on a canvas."),
("How does the AI drawing robot work?", "You press one button, the camera takes your photo, AI makes a line drawing from it, and the arm draws it on canvas."),
("Can the robot draw my portrait?", "Cutshion's AI drawing robot can: it photographs you and draws your picture as a line drawing."),
("Where is the drawing robot used?", "It's popular at events and in education, and brands can print their logo on the backdrop, arm and canvas."),
("Tell me about the cooking robot.", "It's an AI cooking robot for personalised cooking, with Cutshion's own vision and the GOMCOOK platform. It keeps taste and quality the same."),
("Does Cutshion have a chicken robot?", "Yes, Cutshion supplied a chicken-and-beer cooking robot to a restaurant in Itaewon, Seoul."),
("Tell me about the ice cream robot.", "You order on a touch-screen kiosk, and the robot makes soft ice cream and hands it to you, in about 30 seconds."),
("How many cones does the ice cream robot hold?", "It holds 40 cones."),
("What is the candy ball robot?", "A fun event robot: you pick a colour on the touch screen and the robot grabs a candy ball of that colour for you, in about 20 seconds."),
("Tell me about the welding robot.", "It's a lightweight collaborative welding robot that does multi-pass arc welding and follows the seam automatically. The mobile version won the RoboWorld Award 2024."),
("What does the palletizing robot do?", "It stacks finished products on pallets automatically, around the clock. Made with Screen, it's Korea's first palletizing robot for book publishing."),
("What is the educational robot?", "It's a robot training kit in one portable case: a small cobot arm, practice modules, digital twin software and course materials."),
("Do you have robots for schools?", "Yes, Cutshion's educational robot kit is made for schools, universities and labs, and drawing robots have gone to education offices too."),
("What is Pionoid?", "Pionoid is Cutshion's robot development platform: one unified API to control robots from any maker, with an app-store way to share robot apps."),
("What is GOMCOOK?", "GOMCOOK is Cutshion's cooking robot platform. It links to ordering and delivery apps, from order and payment to cooking and delivery."),
("What is CUVision?", "CUVision is Cutshion's AI vision technology: it helps robots understand camera images, for example to check surfaces in factories."),
("Does Cutshion sell robot arms?", "Yes, Cutshion sells collaborative robots from a partner maker, as well as TUSK logistics robots and PEITIAN industrial robots."),
("What is TUSK?", "TUSK robots are logistics robots Cutshion sells: they move pallets on their own and lift up to 1,000 kg."),
("Tell me about PEITIAN.", "PEITIAN industrial robots, sold by Cutshion, carry from 3 to 280 kg."),
("Does Cutshion do design work?", "Yes, Cutshion offers SOLIDWORKS 3D design software and designs robot systems itself."),
],
"ko": [
("쿳션은 어떤 로봇을 만들어요?", "바리스타, AI 드로잉, 조리, 아이스크림, 캔디볼, 용접, 팔레타이징, 교육용 로봇을 만들어요. 어떤 로봇이 궁금하세요?"),
("무슨 로봇 만들어?", "바리스타 로봇, AI 드로잉 로봇, 조리 로봇 같은 여러 로봇 앱을 만들어요. 하나 소개해 드릴까요?"),
("어떤 제품이 있습니까?", "로봇 앱과 AI 비전 큐비전, 로봇 개발 플랫폼 피오노이드, 그리고 로봇 하드웨어가 있습니다. 어느 것을 설명해 드릴까요?"),
("바리스타 로봇은 뭐예요?", "에스프레소 머신을 직접 다뤄서 원두 분쇄, 도징, 탬핑, 추출까지 자동으로 하는 로봇이에요. 언제나 같은 맛을 내요."),
("바리스타 로봇이 뭐야?", "커피를 내리는 로봇이에요. 바리스타의 반복 작업을 맡아서 사람 바리스타와 함께 일해요."),
("바리스타 로봇에 대해 설명해 주십시오.", "바리스타 로봇은 에스프레소 추출 전 과정을 자동으로 하는 올인원 스테이션입니다. 인건비 부담을 줄이고 맛을 일정하게 유지합니다."),
("로봇이 커피도 만들어요?", "네, 쿳션의 바리스타 로봇이 진짜 에스프레소 머신으로 커피를 만들어요."),
("바리스타 로봇은 어디에서 써요?", "메가커피와 연간 공급 계약을 맺었고, 2026년에는 미국에 200대를 공급하는 계약 소식도 있었어요."),
("드로잉 로봇 알려줘.", "AI 드로잉 로봇은 사진을 찍으면 AI가 라인 드로잉으로 바꾸고, 로봇 팔이 캔버스에 그려 줘요."),
("AI 드로잉 로봇은 어떻게 작동해요?", "버튼 하나로 사진을 찍으면 AI가 그림으로 바꾸고 로봇 팔이 그대로 그려요."),
("로봇이 제 얼굴을 그려 줄 수 있습니까?", "네, 쿳션의 AI 드로잉 로봇이 사진을 찍어서 얼굴을 그림으로 그려 줍니다."),
("드로잉 로봇은 어디서 써?", "행사나 교육 현장에서 인기가 많아요. 배경이나 캔버스에 브랜드를 인쇄해서 홍보에도 써요."),
("조리 로봇은 뭐예요?", "개인 맞춤 조리를 지원하는 AI 조리 로봇이에요. 곰쿡 플랫폼과 함께 쓰고 맛과 품질을 일정하게 지켜요."),
("치킨 로봇도 있어?", "네, 이태원 매장에 치맥 조리 로봇을 공급한 적이 있어요."),
("아이스크림 로봇 설명해 줘.", "키오스크로 주문하면 로봇이 아이스크림을 만들어서 직접 건네줘요. 한 개에 약 30초 걸려요."),
("아이스크림 로봇은 콘을 몇 개 넣을 수 있어요?", "콘을 40개 넣을 수 있어요."),
("캔디볼 로봇은 뭐예요?", "터치스크린에서 색을 고르면 로봇이 그 색의 캔디볼을 뽑아서 건네주는 체험형 로봇이에요."),
("용접 로봇도 있어요?", "네, 가벼운 협동 용접 로봇이 있어요. 용접선을 자동으로 따라가고 여러 용접기와 호환돼요."),
("팔레타이징 로봇은 무엇입니까?", "완성품을 팔레트에 자동으로 쌓는 로봇입니다. 스크린사와 함께 만든 국내 최초 출판 전용 팔레타이징 로봇입니다."),
("교육용 로봇 있어?", "네, 협동로봇과 실습 모듈, 디지털 트윈, 교육 자료를 휴대용 케이스에 담은 교육용 키트가 있어요."),
("학교에서 쓸 수 있는 로봇이 있어요?", "교육용 로봇 키트가 학교, 대학, 연구소용으로 나와 있어요."),
("피오노이드가 뭐예요?", "제조사와 상관없이 하나의 통합 로봇 API로 로봇 앱을 만들 수 있는 쿳션의 로봇 개발 플랫폼이에요."),
("곰쿡이 뭐야?", "곰쿡은 배달·주문 앱과 연동되는 쿳션의 조리 로봇 플랫폼이에요."),
("큐비전은 뭐예요?", "큐비전은 카메라 영상을 AI로 이해하는 쿳션의 AI 비전 기술이에요."),
("물류 로봇도 팔아요?", "네, 팔레트를 스스로 옮기는 TUSK 물류로봇을 판매해요. 최대 1,000kg까지 들어요."),
("산업용 로봇도 있습니까?", "네, 3kg부터 280kg까지 다루는 PEITIAN 산업용 로봇을 판매합니다."),
],
},
"location": {
"en": [
("Where is Cutshion?", "Cutshion's head office is in Seoul, in the Mullae SK V1 Center in Yeongdeungpo-gu."),
("Where is your company located?", "In Seoul, Korea: room 709 of the Mullae SK V1 Center, 10 Seonyu-ro 9-gil, Yeongdeungpo-gu."),
("What's the address of Cutshion?", "Room 709, Mullae SK V1 Center, 10 Seonyu-ro 9-gil, Yeongdeungpo-gu, Seoul."),
("Does Cutshion have an office in America?", "Yes, Cutshion has a US company in McLean, Virginia."),
("Do you have a branch in Daegu?", "Yes, Cutshion has a Daegu branch in the Smart Eco Tower in Suseong-gu."),
("Where is the Cutshion factory?", "The Cutshion Mullae Factory is in the same Mullae SK V1 Center building in Seoul, room B135."),
("Where is the research lab?", "Cutshion's research lab is in Magok, Gangseo-gu, Seoul."),
("Does Cutshion have an office in Gangnam?", "Yes, there's a Gangnam office at Venturium, 435 Bongeunsa-ro."),
("Does Cutshion have an office in Japan?", "I don't have information about an office in Japan. Cutshion's places I know are in Seoul, Daegu and McLean in the US."),
("Can I visit the office?", "I don't have information about visits. Please contact Cutshion at 070-8959-2960 to ask."),
],
"ko": [
("회사 어디 있어?", "쿳션 본사는 서울 영등포구 문래 SK V1 Center에 있어요."),
("회사 어디 있어요?", "서울시 영등포구 선유로 9길 10, 문래 SK V1 Center 709호에 있어요."),
("본사는 어디에 있습니까?", "본사는 서울시 영등포구 선유로 9길 10, 문래 SK V1 Center 709호에 있습니다."),
("쿳션 주소 알려줘.", "서울시 영등포구 선유로 9길 10, 문래 SK V1 Center 709호예요."),
("쿳션 공장은 어디예요?", "쿳션 문래 팩토리는 같은 문래 SK V1 Center 건물 B135호에 있어요."),
("대구에도 지사가 있어요?", "네, 대구 수성구 스마트에코타워에 대구지사가 있어요."),
("미국에도 회사가 있어?", "네, 미국 버지니아주 맥린에 미국법인이 있어요."),
("연구소는 어디 있습니까?", "연구소는 서울 강서구 마곡에 있습니다."),
("일본에도 사무실이 있어요?", "일본 사무실에 대한 정보는 없어요. 제가 아는 곳은 서울, 대구, 미국 맥린이에요."),
],
},
"contact": {
"en": [
("How can I contact Cutshion?", "You can call 070-8959-2960, email cutshion@cutshion.com, or use the contact form on cutshion.com."),
("What's Cutshion's phone number?", "It's 070-8959-2960."),
("What's the email of your company?", "cutshion@cutshion.com."),
("What's Cutshion's website?", "It's cutshion.com."),
("I want to buy a robot. Who do I talk to?", "Please contact Cutshion at 070-8959-2960 or cutshion@cutshion.com, or ask a staff member here."),
("Can I buy a barista robot?", "For buying, please contact Cutshion through cutshion.com or at 070-8959-2960. They'll help you with the details."),
("I'd like to become a dealer.", "Cutshion's website has a contact form for dealer questions at cutshion.com, or you can email cutshion@cutshion.com."),
("Does Cutshion have a YouTube channel?", "Yes, Cutshion has a YouTube channel and a blog, linked from cutshion.com."),
],
"ko": [
("쿳션 연락처 알려줘.", "전화 070-8959-2960, 이메일 cutshion@cutshion.com으로 연락하시면 돼요."),
("전화번호가 뭐예요?", "070-8959-2960이에요."),
("이메일 주소가 어떻게 됩니까?", "cutshion@cutshion.com입니다."),
("홈페이지 주소 알려 주세요.", "홈페이지는 cutshion.com이에요."),
("로봇을 사고 싶은데 어떻게 해요?", "070-8959-2960이나 cutshion@cutshion.com으로 문의하시거나, 여기 직원에게 물어보세요."),
("바리스타 로봇 살 수 있어?", "구매는 쿳션에 직접 문의해 주세요. 홈페이지 cutshion.com의 문의하기를 쓰시면 돼요."),
("대리점 하고 싶습니다.", "홈페이지 cutshion.com의 문의하기에서 대리점 문의를 하실 수 있습니다."),
],
},
"achievements": {
"en": [
("What awards has Cutshion won?", "The RoboWorld Award in 2023 and 2024, and the VivaTech Tech for Change Award in Paris in 2026."),
("Did Cutshion go to CES?", "Yes, Cutshion exhibited at CES in Las Vegas in 2025 and 2026."),
("Who are Cutshion's partners?", "Its partners include OMRON, Zimmer Group Korea, Screen HD Korea and Daesung Industrial, among others."),
("Has Cutshion received investment?", "Yes, a seed investment of 500 million won in 2025, and it was selected for the TIPS Global Track."),
("What exhibitions has Cutshion been to?", "RoboWorld, IFA Berlin, CES in Las Vegas, the NRA Show in Chicago and VivaTech in Paris, among others."),
],
"ko": [
("상 받은 거 있어요?", "로보월드 어워드를 2023년과 2024년에 받았고, 2026년 비바테크에서 Tech for Change Award를 받았어요."),
("CES에 나갔어?", "네, 2025년과 2026년 CES에 참가했어요."),
("파트너 회사는 어디예요?", "오므론, 짐머그룹코리아, 스크린에이치디코리아, 대성산업 등이 있어요."),
("투자 받았습니까?", "네, 2025년에 5억 원 규모 시드 투자를 받았고 TIPS 글로벌트랙에도 선정됐습니다."),
],
},
"services": {
"en": [
("What services does Cutshion offer?", "Cutshion develops robot apps and smart factory solutions, sells robot hardware and SOLIDWORKS design software, and designs robot systems. Which would you like to know about?"),
("Does Cutshion do smart factories?", "Yes, Cutshion builds smart factory solutions with AI vision, collaborative robots and mobile robots."),
("Can Cutshion automate my factory?", "Cutshion makes factory automation with AI vision, cobots and mobile robots. For your case, please contact them at 070-8959-2960."),
("Does Cutshion make software?", "Yes, robot software is its core: robot apps, the Pionoid robot platform and CUVision AI vision."),
("Does Cutshion work with restaurants?", "Yes, its cooking robot and the GOMCOOK platform are made for restaurants, and the barista robot for cafes."),
("Can Cutshion's robots work at events?", "Yes, the AI drawing robot, ice cream robot and candy ball robot are popular at events."),
("Does Cutshion sell SOLIDWORKS?", "Yes, Cutshion offers SOLIDWORKS design software and helps customers pick the right products."),
("Can robots from different makers use the same app?", "That's the idea of Cutshion's Pionoid platform: one unified API, so one app can run on robots from different makers."),
("Does Cutshion do custom robots?", "The palletizing robot, for example, can be adapted to each factory. For your own project, please contact Cutshion at cutshion@cutshion.com."),
("What industries does Cutshion work in?", "Cafes and restaurants, factories and logistics, events, and education."),
],
"ko": [
("쿳션은 어떤 서비스를 해요?", "로봇 앱과 스마트 팩토리 솔루션을 개발하고, 로봇 하드웨어와 솔리드웍스 설계 소프트웨어도 공급해요. 어떤 게 궁금하세요?"),
("스마트 팩토리도 해?", "네, AI 비전과 협동로봇, AMR로 스마트 팩토리 솔루션을 만들어요."),
("우리 공장도 자동화할 수 있습니까?", "쿳션이 공장 자동화 솔루션을 만들고 있습니다. 자세한 건 070-8959-2960으로 문의해 주세요."),
("소프트웨어도 만들어요?", "네, 로봇 앱, 피오노이드 플랫폼, 큐비전 AI 비전 같은 소프트웨어가 핵심이에요."),
("식당에서 쓸 로봇도 있어?", "네, 조리 로봇과 곰쿡 플랫폼은 식당용이고, 바리스타 로봇은 카페용이에요."),
("행사에 쓸 만한 로봇 있어요?", "AI 드로잉 로봇, 아이스크림 로봇, 캔디볼 로봇이 행사에서 인기가 많아요."),
("솔리드웍스도 팝니까?", "네, 솔리드웍스 설계 소프트웨어를 공급하고 알맞은 제품 구성도 함께 검토해 드립니다."),
("어떤 분야에서 일해요?", "카페와 식당, 공장과 물류, 행사, 교육 분야에서 일해요."),
],
},
"follow_up": {
"en": [
("And what else?", "Cutshion also makes cooking, ice cream, candy ball, welding and educational robots. Which one sounds interesting?"),
("What else does Cutshion make?", "Besides the barista and drawing robots, there's a cooking robot, an ice cream robot, a candy ball robot, a welding robot and more. Shall I describe one?"),
("Tell me more.", "Happy to. Which part would you like more on: the robots, where Cutshion is, or how to contact it?"),
("Tell me more about the barista robot.", "It works with a real espresso machine, grinding, dosing, tamping and extracting by itself, and a yearly supply deal was signed with Mega Coffee."),
("How does the barista robot work?", "It controls a real espresso machine: it grinds the beans, doses, tamps and extracts the espresso by itself."),
("Tell me more about the drawing robot.", "It takes your photo with a camera, AI turns it into a line drawing, and the arm draws it on canvas. It comes as an all-in-one or a kiosk type."),
("Anything else?", "Cutshion also has its own AI vision, CUVision, and a robot platform called Pionoid. Want to hear about those?"),
("Interesting, go on.", "Cutshion's goal is to be a robot platform company, so the same robot app can run on robots from different makers."),
("How does the ice cream robot work?", "You order on the kiosk, the robot makes the soft ice cream and hands it to you, in about 30 seconds."),
("Which robot is the most popular?", "I don't have that information. I can tell you about each robot, though. Which one?"),
],
"ko": [
("또 뭐 있어?", "조리 로봇, 아이스크림 로봇, 캔디볼 로봇, 용접 로봇, 교육용 로봇도 있어요. 어떤 게 궁금하세요?"),
("그리고요?", "AI 비전 기술 큐비전과 로봇 개발 플랫폼 피오노이드도 있어요. 소개해 드릴까요?"),
("더 자세히 알려줘.", "네, 로봇, 회사 위치, 연락처 중에 어떤 걸 더 알려 드릴까요?"),
("바리스타 로봇 더 자세히 알려 주세요.", "진짜 에스프레소 머신으로 원두 분쇄, 도징, 탬핑, 추출을 스스로 해요. 메가커피와 연간 공급 계약도 맺었어요."),
("바리스타 로봇은 어떻게 작동해요?", "에스프레소 머신을 직접 다뤄서 원두 분쇄, 도징, 탬핑, 추출을 차례로 스스로 해요."),
("다른 로봇도 있습니까?", "네, 바리스타와 드로잉 로봇 말고도 조리, 아이스크림, 캔디볼, 용접, 팔레타이징 로봇이 있습니다."),
("제일 인기 있는 로봇은 뭐야?", "그 정보는 없어요. 대신 로봇 하나씩 소개해 드릴 수 있어요."),
("드로잉 로봇은 어떻게 그려요?", "카메라로 사진을 찍으면 AI가 라인 드로잉으로 바꾸고, 로봇 팔이 캔버스에 그려요."),
],
},
"unknown": {
"en": [
("How much does the barista robot cost?", "I don't have price information. Please ask a staff member or contact Cutshion at 070-8959-2960."),
("What's the price of the drawing robot?", "Sorry, I don't know the price. Cutshion can tell you at cutshion@cutshion.com."),
("How much is the ice cream robot?", "I don't have that information. A staff member or Cutshion's contact form can help with prices."),
("How much do you cost?", "I don't know my own price, I'm afraid. Please ask a staff member."),
("Can I rent a robot? How much per month?", "I don't have information about rental or prices. Please contact Cutshion to ask."),
("Do you give a discount?", "I don't have information about discounts. Cutshion's team can answer that."),
("How many people work at Cutshion?", "I don't have that information, sorry."),
("How many employees does your company have?", "I'm not sure, the number of employees isn't something I know."),
("What is Cutshion's revenue?", "I don't have information about Cutshion's revenue."),
("Is Cutshion profitable?", "That's not something I have information about, sorry."),
("Is Cutshion listed on the stock market?", "I'm not sure about that, I don't have the information."),
("How much is Cutshion worth?", "I don't know the company's value, I'm afraid."),
("Is Cutshion hiring?", "I don't have information about jobs. You could email cutshion@cutshion.com to ask."),
("How can I get a job at Cutshion?", "I don't know about job openings. Contacting cutshion@cutshion.com would be the way to ask."),
("What are Cutshion's office hours?", "I don't have information about office hours."),
("How long does delivery take?", "I don't know delivery times. Cutshion can tell you if you contact them."),
("What warranty do your robots have?", "I don't have information about the warranty. Please ask Cutshion directly."),
("How many robots has Cutshion sold?", "I don't have the total number, sorry."),
("How old is the CEO?", "I don't know the CEO's age."),
("How many customers does Cutshion have?", "I'm not sure. I only know a few projects, like the supply agreement with Mega Coffee."),
("What's the cheapest robot Cutshion sells?", "I don't have price information, so I can't compare. Cutshion's team can help at 070-8959-2960."),
("Does Cutshion ship to Europe?", "I don't have information about shipping to Europe. Please ask Cutshion directly."),
("Who are Cutshion's competitors?", "I don't have that information."),
("How much did the US contract cost?", "I'm not sure about contract details. I only know that 200 barista robots are to be supplied over three years."),
("Is there a Cutshion shop I can visit?", "I don't have information about a shop. Cutshion's contact is 070-8959-2960 if you'd like to ask."),
("What does Cutshion plan next year?", "I don't have information about Cutshion's plans."),
],
"ko": [
("바리스타 로봇 얼마예요?", "가격 정보는 없어요. 직원에게 물어보시거나 070-8959-2960으로 문의해 주세요."),
("바리스타 로봇 가격이 얼마야?", "죄송하지만 가격은 몰라요. cutshion@cutshion.com으로 문의하시면 돼요."),
("드로잉 로봇은 가격이 얼마입니까?", "가격은 제가 알지 못합니다. 쿳션에 문의해 주세요."),
("너는 얼마야?", "제 가격은 저도 몰라요. 직원에게 물어봐 주세요."),
("로봇 렌탈도 돼요?", "렌탈에 대한 정보는 없어요. 쿳션에 직접 문의해 주세요."),
("직원은 몇 명이에요?", "그 정보는 없어요."),
("회사 직원 몇 명이야?", "직원 수는 제가 알지 못해요."),
("쿳션에는 몇 명이 일합니까?", "죄송하지만 그 정보는 가지고 있지 않습니다."),
("매출이 얼마예요?", "매출 정보는 없어요."),
("쿳션은 상장했어?", "그건 잘 모르겠어요. 정보가 없어요."),
("채용하고 있어요?", "채용 정보는 없어요. cutshion@cutshion.com으로 문의해 보세요."),
("쿳션에 취업하려면 어떻게 해야 합니까?", "채용에 대해서는 알지 못합니다. 이메일로 쿳션에 문의해 주세요."),
("회사 영업시간이 어떻게 돼요?", "영업시간 정보는 없어요."),
("로봇 배송은 얼마나 걸려?", "배송 기간은 몰라요. 쿳션에 문의하시면 알려 줄 거예요."),
("보증 기간은 얼마나 됩니까?", "보증 조건은 알지 못합니다. 쿳션에 직접 문의해 주세요."),
("지금까지 로봇 몇 대 팔았어요?", "전체 판매 대수는 몰라요."),
("대표님 나이가 어떻게 돼요?", "대표님 나이는 제가 몰라요."),
("할인돼요?", "할인 정보는 없어요. 직원에게 물어봐 주세요."),
],
},
"topic_switch": {
"en": [
("Thanks. By the way, how old are you?", "I'm two years old."),
("Okay. What's your name again?", "I'm Lumi."),
("Got it. Can you speak Korean?", "Yes, I speak English and Korean."),
("Cool. Can you sing?", "I can sing a short song. Want to hear it?"),
("Alright. What's two plus two?", "Four."),
("Never mind the company. Are you a robot?", "Yes, I'm a robot, a mobile robot assistant."),
("Okay, different question: can you pick up a cup?", "Yes, I can pick up cups, bottles and some fruit with my arm."),
("Thanks. Where is the restroom?", "I'm not sure where the restroom is here. A staff member can show you."),
("Enough about robots. Do you like music?", "I do enjoy a good tune, and I can even sing a little."),
("Fine. What's the capital of France?", "Paris."),
("Anyway, how tall are you?", "I'm 146 cm tall, and I can stretch up to 186 cm."),
("Let's talk about something else. Tell me a joke.", "Why did the robot go on holiday? It needed to recharge."),
("Okay. Can you wave at me?", "Sure, here's a wave for you!"),
("Good to know. How fast can you drive?", "I usually drive at 0.6 metres per second, at most 1.2."),
],
"ko": [
("고마워. 그런데 너 몇 살이야?", "저는 두 살이에요."),
("알겠어요. 이름이 뭐였죠?", "저는 루미예요."),
("좋아. 영어도 할 수 있어?", "네, 영어와 한국어를 할 수 있어요."),
("그래요. 노래할 수 있어요?", "짧은 노래를 부를 수 있어요. 들어 보실래요?"),
("알겠습니다. 2 더하기 2는 무엇입니까?", "4입니다."),
("회사 얘기는 됐고, 너 로봇이야?", "네, 저는 이동형 로봇 도우미예요."),
("그건 그렇고, 컵 집을 수 있어요?", "네, 팔로 컵이나 병, 과일 같은 걸 집을 수 있어요."),
("고마워요. 화장실은 어디예요?", "여기 화장실 위치는 잘 몰라요. 직원에게 물어봐 주세요."),
("다른 얘기 하자. 농담 하나 해 줘.", "로봇이 휴가를 간 이유가 뭘까요? 충전이 필요해서예요."),
("그런데 키가 얼마나 돼요?", "제 키는 146cm이고, 186cm까지 늘어날 수 있어요."),
("알겠어. 손 흔들어 줄래?", "네, 손 흔들어 드릴게요!"),
("됐어요. 프랑스 수도는 어디예요?", "파리예요."),
("좋네요. 얼마나 빨리 움직여요?", "보통 초속 0.6미터로 다니고, 가장 빠르면 1.2미터예요."),
],
},
}
EXAMPLES = [(cat, lang, said, reply)
for cat, langs in _BANK.items() for lang, pairs in langs.items() for said, reply in pairs]
if __name__ == "__main__":
from collections import Counter
from assistant import talk_examples
if len(sys.argv) > 1:
text = " ".join(sys.argv[1:])
for ex in talk_examples.pick(text, "ko" if re.search("[가-힣]", text) else "en", bank=EXAMPLES):
print(ex)
sys.exit()
langs = Counter(e[1] for e in EXAMPLES)
for cat in _BANK:
print(f"{cat:14s} en {len(_BANK[cat]['en']):3d} ko {len(_BANK[cat]['ko']):3d}")
print(f"total {len(EXAMPLES)}: en {langs['en']}, ko {langs['ko']} ({langs['ko'] / len(EXAMPLES):.0%} Korean)")
assert len(EXAMPLES) >= 250, len(EXAMPLES)
assert 0.40 <= langs["ko"] / len(EXAMPLES) <= 0.50, langs
assert not any(re.search(r"jaka|자카", e[2] + e[3], re.I) for e in EXAMPLES)
assert not any(re.search(r"컷션|커션", e[2] + e[3]) for e in EXAMPLES) # the site writes 쿳션
assert not any(re.search("[가-힣]", e[3]) for e in EXAMPLES if e[1] == "en")
rude = [e[3] for e in EXAMPLES if e[1] == "ko" and not talk_examples.polite(e[3])]
assert not rude, rude
for cat in _BANK:
have = {talk_examples.level(s) for c, lang, s, _ in EXAMPLES if c == cat and lang == "ko"}
assert have == {"casual", "polite", "formal"}, (cat, have)
repeated = [r for r, n in Counter(e[3] for e in EXAMPLES).items() if n > 1]
assert not repeated, repeated
print("ok")
+228
View File
@@ -0,0 +1,228 @@
"""Short drives and the drive speed as people say them, in English, Korean and mixed, with whisper's slips.
which way and how far: "come back 20 cm", "move back 5 centimeters", "20센티 뒤로", "앞으로 반 미터",
"back up a tiny bit", "a hair to the left", "살짝 뒤로", "한 뼘 앞으로", "two steps back", "반 걸음 뒤로"
faster / slower: "a little faster", "can you pick up the pace", "not so fast", "ease off", "slow it down a notch",
"way too slow", "너무 빨라", "좀 천천히 가 줄래요", "속도 줄여"
after one of them: "more", "again", "a bit more", "same again", "조금 더", "한 번 더", "just a few centimetres more"
Reads text normalised by brain._norm (wording.norm: "20 cm" -> "0.2 m", "이십 센티" -> "0.2 m", "two" -> "2").
Nothing is guessed: a number said without a unit that is read is asked about, a drive past MOVE_MAX_M is refused
with the limit, "more" with nothing before it is asked about.
python assistant/driving.py "back up a tiny bit"
"""
import re
import sys
MOVE_MAX_M = 3.0 # m; the longest short drive (lumi.MAX_MOVE_M); longer is refused with this limit
MOVE_MIN_M = 0.01 # m; a shorter drive is refused
DEFAULT_M = 1.0 # m; "move back" with no amount (as before)
LITTLE_M = 0.5 # m; "a little", "a bit", "조금", "좀" (as before)
TINY_M = 0.05 # m; "a tiny bit", "a hair", "a few centimetres", "살짝"; estimate
SPAN_M = 0.2 # m; "한 뼘", one hand span; estimate
STEP_M = 0.5 # m; one step ("two steps", "한 걸음", "반 걸음"); estimate of a person's step
DIRS = (("back", r"\bback(?:wards?)?\b|\bbackward\b|\breverse\b|^(?:let'?s )?(?:bake|big)\b(?= \d| half| a )|뒤로|뒤쪽|후진|"
r"물러"), # whisper's "let's bake / big one meter"
("forward", r"\bforwards?\b|\bahead\b|앞으로|앞쪽|전진"),
("left", r"\b(?:to the |to your )?left\b|왼쪽|좌측"),
("right", r"(?<!all )\b(?:to the |to your )?right\b(?! now| away| here| there| back)|오른쪽|우측"))
VERB = re.compile(r"\b(?:move|go|come|drive|step|scoot|scooch|shift|inch|roll|back (?:up|off)|reverse|get)\b|"
r"가|와|이동|움직|물러|빠져|후진|전진|비켜")
OTHER = re.compile(r"\b(?:look|head|turn|rotate|face|arm|hand|lift|raise|lower|it|this|that|them|those|these|here|there|"
r"home|me|us)\b|\bthe (?!left\b|right\b)|\bgo (?:right )?ahead\b|\bback to (?![\d.])|\bp\d+\b|고개|머리|팔|손|돌아|돌려|봐|쳐다|들어|올려|내려|"
r"여기|저기|이리|집|\S(?:을|를)(?=\s)") # the head, an object, a place: not a short drive
SAYER = re.compile(r"\b(?:i|i'm|im|i'll|i've|we|we're|he|she|they|there|it's|it is|my|our|his|her|their|was|were|"
r"if|when)\b|(?:^|\s)(?:나|저|우리|저희)(?:는|도|가)\s") # "I live a few metres to the left"
_NATIVE = {"한": 1, "두": 2, "세": 3, "네": 4, "다섯": 5, "여섯": 6, "일곱": 7, "여덟": 8, "아홉": 9, "열": 10,
"a": 1, "an": 1, "half": 0.5, "반": 0.5}
_COUNT = rf"(\d+(?:\.\d+)?|{'|'.join(_NATIVE)})\s*(?:a\s+)?"
STEPS = re.compile(rf"(?:(?<![\w.]){_COUNT}\s*)?(?:steps?|paces?|걸음|발짝|발자국)(?![a-z])")
SPANS = re.compile(rf"(?:(?<![\w.]){_COUNT}\s*)?뼘")
TINY = re.compile(r"\b(?:tiny|teeny|wee|hair|hairs?breadth|smidge|smidgen|tad|touch|nudge|slightly|little tiny)\b|"
r"\bfew (?:centimet(?:er|re)s|cm)\b|\binch (?:forward|back|left|right|ahead)|"
r"살짝|아주 조금|쪼끔|쬐끔|약간|요만큼|조금만 살짝")
LITTLE = re.compile(r"\b(?:a little|a bit|little bit|bit)\b|조금|좀|쪼금")
NUM_WORD = re.compile(r"\b(?:eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|"
r"thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|dozen|couple|several|few|half)\b")
FASTER = re.compile(r"\b(?:faster|quicker|speed (?:it )?up|pick up (?:the )?(?:pace|speed)|step on it|hurry(?: up)?|"
r"get a move on|more speed|full speed|go quick(?:ly)?|too slow(?:ly)?|so slow(?:ly)?|"
r"not fast enough|move it)\b|빨리|빠르게|속도\s*(?:를|좀)?\s*(?:좀\s*)?(?:높|올)\S*|느려|느리다|서둘러")
SLOWER = re.compile(r"\b(?:slower|slow (?:it )?down|slow|ease (?:off|up)|not so fast|too fast|"
r"so fast|less speed|gently|more slowly|slowly)\b|"
r"천천히|느리게|속도\s*(?:를|좀)?\s*(?:좀\s*)?(?:줄|낮|늦)\S*|빨라|빠르다|살살")
_FILLER = (r"please|pls|lumi|hey|hi|okay|ok|so|um+|uh+|well|now|then|just|can|could|would|will|you|you're|youre|"
r"are|is|going|moving|driving|go|drive|move|"
r"keep|going|get|it|the|a|an|bit|little|tiny|notch|touch|tad|lot|much|way|even|bit|slightly|somewhat|"
r"more|than|that|this|let's|lets|try|be|bit\.|maybe|yeah|yes|alright|right|bro|man|too|really|"
r"루미야|루미|좀|조금|조금만|더|약간|살짝|이제|그냥|너무|가|가줘|가 ?줘|가요|가세요|줘|주세요|줄래|줄래요|"
r"줄래\?|주실래요|주시겠어요|해|해줘|해요|해 ?줘|움직여|요|좀더|조금더|자|볼래|봐|볼까|좀만|해봐")
FILL = re.compile(rf"(?:^|\s)(?:{_FILLER})(?=\s|$)")
AGAIN = re.compile(r"^(?:(?:just|a|an|bit|little|tiny|some|even|one|once|the|same|do|it|that|go|please|lumi|ok|"
r"okay|yeah|yes|and|then|now)\s+)*(?:more|again|once more|one more time|same again|"
r"the same again|more please|again please|1 more time)(?:\s+(?:please|lumi|then))?$|"
r"^(?:루미야\s+)?(?:조금만?|좀|살짝|약간|한 ?번|1 ?번|아까처럼|똑같이)?\s*더"
r"(?:\s*(?:가|해|가 ?줘|해 ?줘|가요|해요|가 ?주세요|해 ?주세요))?$|^한 ?번 ?더|^똑같이(?: 해| 한 ?번)?")
LESS = re.compile(r"^(?:(?:a|bit|little|just|a little|a bit)\s+)*less(?: please)?$|^(?:좀|조금)?\s*덜$")
JOINED = re.compile(r"\b(?:and|then|after that|and then)\b|그리고|하고|해서|가서|다음에|집어|가져")
def clean(t):
return re.sub(r"\s+", " ", re.sub(r"[,!?~…]+|(?<!\d)\.|\.(?!\d)", " ", (t or "").lower())).strip()
def direction(t):
return next((d for d, rx in DIRS if re.search(rx, t)), None)
def amount(t):
"""(metres, exact) said in normalised text: exact for a number with a unit ("0.2 m"), else the estimate a vague
word stands for; (None, False) when no amount is said; ("?", False) for a number without a unit that is read."""
m = re.search(r"(?<![\w.])(\d+(?:\.\d+)?) m(?![a-z])", t)
if m:
return float(m.group(1)), True
if TINY.search(t):
return TINY_M, False
for rx, unit in ((STEPS, STEP_M), (SPANS, SPAN_M)):
m = rx.search(t)
if m and not re.search(r"\b(?:few|couple|several|some)\b", t):
n = m.group(1)
return (float(n) if n and n[0].isdigit() else _NATIVE.get(n, 1)) * unit, False
if re.search(r"(?<![\w.])\d", t) or NUM_WORD.search(t):
return "?", False # "move back 20", "two feet", "a couple of metres"
if LITTLE.search(t):
return LITTLE_M, False
return None, False
def move(t, verb_needed=True):
"""(direction, metres | "?", exact) for one short drive in normalised text, or None. Without a drive verb an
amount must be said ("a hair to the left", "살짝 뒤로"); a sentence about someone else is not a drive."""
t = clean(t)
d = direction(t)
if d is None or JOINED.search(t) or SAYER.search(t) or OTHER.search(t):
return None
n, exact = amount(t)
if verb_needed and n is None and not VERB.search(t):
return None
if n is None:
n = DEFAULT_M
return d, n, exact
def speed(t):
"""+1 (faster) / -1 (slower) when the whole sentence asks for a speed change, else 0."""
t = clean(t)
too = re.search(r"\b(?:too|so|way too) (fast|slow)\b|(?:너무|넘) ?(빨라|느려)", t)
if too:
sign = -1 if too.group(1) == "fast" or too.group(2) == "빨라" else 1
else:
fast, slow = FASTER.search(t), SLOWER.search(t)
if bool(fast) == bool(slow):
return 0
sign = 1 if fast else -1
rest = FILL.sub(" ", FILL.sub(" ", SLOWER.sub(" ", FASTER.sub(" ", t))))
rest = re.sub(r"\b(?:too|so|way|fast|slow|the pace|pace|speed|down|it)\b|(?:^|\s)(?:속도|를)(?=\s|$)", " ", rest)
return sign if not rest.strip() else 0
def read(t, last=None, talking=False):
"""What a sentence asks of the base, or None (not about driving):
("move", "back 0.2", exact) | ("speed", +1 | -1) | ("refuse", "back 5") | ("ask", "back" | "").
`last` is the move / speed just before (last_command(history)): "more" / "again" repeat it. With none and
`talking` (the turn before was conversation) "more" is left to the conversation, else it is asked about."""
t = clean(t)
s = speed(t)
if s:
return ("speed", s)
if AGAIN.search(t) or LESS.search(t):
if last is None:
return None if talking else ("ask", "") # "more" of what?
if LESS.search(t):
return ("speed", -1) if last[0] == "speed" else None
return last
if last and last[0] == "move" and re.search(r"\bmore\b|더", t) and direction(t) is None and not JOINED.search(t):
n, exact = amount(t) # "just a few centimetres more", "10센티 더"
if n is not None:
return _checked(last[1].split()[0], n, exact)
got = move(t)
return _checked(*got) if got else None
def _checked(d, n, exact):
if n == "?":
return ("ask", d)
if n > MOVE_MAX_M or n < MOVE_MIN_M:
return ("refuse", f"{d} {n:g}")
return ("move", f"{d} {n:g}", exact)
def last_command(history):
"""The move or speed change of the turn just before, from brain history ("ACTION: move back 0.2"), else None."""
if not history:
return None
m = re.match(r"ACTION: (move|speed) (\S+)(?: (\S+))?", history[-1][1] or "")
if not m:
return None
if m.group(1) == "speed":
return ("speed", int(m.group(2)))
return ("move", f"{m.group(2)} {m.group(3)}", True) if m.group(3) else None
def talking(history):
"""The turn before was conversation (not a command): a bare "more" belongs to it."""
return bool(history) and bool(re.match(r"ACTION: none\b|(?!ACTION:)", history[-1][1] or ""))
def spoken(m, lang="en"):
"""0.2 -> "20 centimetres" / "20센티", 1.5 -> "1.5 metres" / "1.5미터"."""
if m >= 1:
return f"{m:g} metre{'' if m == 1 else 's'}" if lang == "en" else f"{m:g}미터"
if m >= 0.01:
cm = round(m * 100, 1)
return f"{cm:g} centimetre{'' if cm == 1 else 's'}" if lang == "en" else f"{cm:g}센티"
return f"{m * 1000:g} millimetres" if lang == "en" else f"{m * 1000:g}밀리"
KO_DIR = {"forward": "앞으로", "back": "뒤로", "left": "왼쪽으로", "right": "오른쪽으로"}
def say_move(d, m, exact, lang="en"):
"""The read-back of a drive; "about" when the amount was not said exactly."""
if lang == "en":
return f"Okay, moving {d} {'' if exact else 'about '}{spoken(m)}."
return f"네, {KO_DIR.get(d, '')} {'' if exact else '약 '}{spoken(m, 'ko')} 갈게요."
def say_refused(d, n, lang="en"):
if n < MOVE_MIN_M:
return ("Sorry, that's too short for me to drive." if lang == "en" else "죄송해요, 너무 짧아서 갈 수 없어요.")
return (f"Sorry, I can only drive up to {spoken(MOVE_MAX_M)} at a time." if lang == "en"
else f"죄송해요, 한 번에 {spoken(MOVE_MAX_M, 'ko')}까지만 갈 수 있어요.")
def say_ask(d, lang="en"):
if not d:
return ("More of what? Please tell me what to do." if lang == "en" else "무엇을 더 할까요? 다시 말씀해 주세요.")
return (f"How far should I go {d}? Please say it with a unit, like 20 centimetres." if lang == "en"
else f"{KO_DIR.get(d, '')} 얼마나 갈까요? 20센티처럼 단위와 함께 말씀해 주세요.")
def say_speed(sign, factor, changed, lang="en"):
"""The answer to a speed change: the new speed in plain words."""
pct = round(factor * 100)
if not changed:
return (("I'm already at my top speed." if sign > 0 else "I'm already at my slowest.") if lang == "en"
else ("이미 가장 빠른 속도예요." if sign > 0 else "이미 가장 느린 속도예요."))
if pct == 100:
return "Okay, back to my normal speed." if lang == "en" else "네, 보통 속도로 갈게요."
if lang == "en":
return f"Okay, a bit {'faster' if sign > 0 else 'slower'}: {pct} percent of my normal speed."
return f"네, 조금 더 {'빨리' if sign > 0 else '천천히'} 갈게요. 보통 속도의 {pct}퍼센트예요."
if __name__ == "__main__":
from assistant import brain
print(read(brain._norm(" ".join(sys.argv[1:]))))
+93
View File
@@ -0,0 +1,93 @@
"""Voice confirmation of a fetch task (docs/16 §4): read the task back, listen, start / correct / cancel.
The robot parts are passed in, so this runs the same in lumi.py and in tests/test_fetch_intents.py:
listen(seconds) -> (text or None on silence, understood)
say(en, ko) -> speaks one of them in the current language
describe(task, lang) -> the read-back sentence (tasks/fetch.py)
start(task) -> starts the task (lumi.py turns "here" into the robot's pose first)
"""
from assistant import brain
CONFIRM_S = 5.0 # s to wait for the answer to a question
MAX_ROUNDS = 3 # questions asked before Lumi gives up
def _question(task, markers):
"""(en, ko) asking for the first missing field, or None when the task is complete."""
places = ", ".join(markers)
if task.get("object") is None:
from tasks import fetch # what the fingers can pick (skills.GRASPS)
en, ko = [n for n in fetch.PICKABLE], [fetch.OBJECTS[n] for n in fetch.PICKABLE]
return (f"Which object? I can pick up {', '.join(en[:-1])} and {en[-1]}.",
f"어떤 물건이요? {', '.join(ko)}{'을' if (ord(ko[-1][-1]) - 0xAC00) % 28 else '를'} 집을 수 있어요.")
if task.get("source") is None:
return (f"Where should I take it from? I know {places}.", f"어디에서 가져올까요? {places}를 알아요.")
if task.get("dest") is None:
return (f"Where should I bring it? I know {places}, or here.", f"어디로 가져갈까요? {places} 또는 여기요.")
return None
def _field(task):
"""The field a bare answer ("p2") is about: the first missing place."""
return next((f for f in ("source", "dest") if task.get(f) is None), None)
def run(task, markers, listen, say, describe, start):
"""Ask until the task is complete and confirmed. Returns 'started', 'cancelled' or 'gave_up'."""
prompt = True # False: just listen again (after "sorry" / "what to change")
readback = False # the last thing asked was "Is that right?"
for _ in range(MAX_ROUNDS):
if prompt:
q = _question(task, markers)
readback = q is None
if readback:
q = (describe(task, "en") + " Is that right?", describe(task, "ko") + " 맞아요?")
say(*q)
prompt = True
text, understood = listen(CONFIRM_S)
if not text:
if readback: # silence after the read-back = yes
start(task)
return "started"
say("Okay, cancelled.", "네, 취소할게요.")
return "cancelled"
if not understood:
say("Sorry, I didn't catch that.", "죄송해요, 잘 못 들었어요.")
prompt = False
continue
answer = brain.confirm_answer(text)
if answer == "cancel":
say("Okay, cancelled.", "네, 취소할게요.")
return "cancelled"
if readback and answer == "yes":
start(task)
return "started"
task, changed = brain.parse_correction(text, task, markers, field=_field(task))
if not changed and readback: # "no" alone, or words that change nothing
say("What should I change?", "무엇을 바꿀까요?")
prompt = readback = False
# not readback and nothing changed: the same question is asked again
say("Sorry, let's try again later.", "죄송해요, 나중에 다시 해요.")
return "gave_up"
def run_steps(steps, listen, say, describe, start):
"""Voice confirmation of a mission (docs/17): read the steps back, start only on a spoken yes (a mission drives
and moves the arm: silence is asked again, then cancelled). A no cancels it: a mission is said again as a whole,
not corrected piece by piece. Returns 'started' or 'cancelled'."""
say(describe(steps, "en") + " Is that right?", describe(steps, "ko") + " 맞아요?")
for _ in range(MAX_ROUNDS):
text, understood = listen(CONFIRM_S)
if not text:
say("Should I do it? Please say yes or no.", "할까요? 네 또는 아니요로 말해 주세요.")
continue
if not understood:
say("Sorry, I didn't catch that. Is that right?", "죄송해요, 잘 못 들었어요. 맞아요?")
continue
answer = brain.confirm_answer(text)
if answer == "yes":
start(steps)
return "started"
break
say("Okay, I won't do it. Please say the whole command again.", "네, 안 할게요. 전체 명령을 다시 말씀해 주세요.")
return "cancelled"
+371
View File
@@ -0,0 +1,371 @@
"""Few-shot examples for deciding what to do with something said to Lumi while it is on a mission (docs/17).
EXAMPLES = [(state, who, utterance, decision, reply)]
- state: what Lumi is doing and for whom; who: stranger | recipient | sender | owner (as far as known).
- decision: halt_talk, answer, refuse_redirect, give_here, change_task, cancel, safety_stop, resume, ask_language.
halt_talk: halt, turn to them, greet. answer: answer, then ask whether it may go on. refuse_redirect: keep the
mission, say who it is for, offer help after. give_here: the recipient named themself, hand it over now.
change_task / cancel: only the recipient, the sender or the owner. safety_stop: halt until told to go on.
resume: they have nothing for Lumi (goodbye, "go on", yes to "may I go on?").
- reply: what Lumi says, in the speaker's language ("" = nothing to say).
"""
J = "driving to p6 with a cup for James"
J_STOP = "halted on the way to p6 with a cup for James, talking"
J_SAFE = "safety stop on the way to p6 with a cup for James"
J_GIVE = "giving the cup to James at p6"
M = "driving to final with a bottle for Mina, sent by Anvar"
M_STOP = "halted on the way to final with a bottle for Mina (from Anvar), talking"
T = "turning towards p9 with an apple for Tom, sent by Lisa"
P = "picking the cup, then bringing it to Sara at p3"
KJ = "driving to p6 with a cup for 제임스"
KJ_STOP = "halted on the way to p6 with a cup for 제임스, talking"
KJ_SAFE = "safety stop on the way to p6 with a cup for 제임스"
KJ_GIVE = "giving the cup to 제임스 at p6"
KM = "driving to final with a bottle for 미나, sent by 안바르"
KM_STOP = "halted on the way to final with a bottle for 미나 (from 안바르), talking"
KH = "driving to p8 with an apple for 현우, sent by 지은"
KP = "picking the cup, then bringing it to 민수 at p3"
HI = "Hi, I'm Lumi. How can I help you?"
KHI = "안녕하세요, 저는 루미예요. 무엇을 도와드릴까요?"
BYE = "Goodbye! I'll go on with my task."
KBYE = "안녕히 계세요! 하던 일 계속할게요."
LANG = "Sorry, I understand only English and Korean. 영어나 한국어로 말씀해 주세요."
J_TASK = "I'm bringing a cup to James at p6."
KJ_TASK = "p6에 있는 제임스 님께 컵을 가져다드리는 중이에요."
J_NO = "Sorry, I'm bringing this cup to James at p6. I can help you after that."
KJ_NO = "죄송해요, 지금 p6에 있는 제임스 님께 컵을 가져다드리는 중이에요. 끝나고 도와드릴게요."
M_NO = "Sorry, I'm taking this bottle to Mina at final for Anvar. I can help you after that."
KM_NO = "죄송해요, 안바르 님 부탁으로 final에 있는 미나 님께 병을 가져다드리는 중이에요. 끝나고 도와드릴게요."
GO = " Can I go on with my task?"
KGO = " 하던 일 계속 가도 될까요?"
SAFE = "Stopped."
KSAFE = "멈췄어요."
EXAMPLES = [
# ================= English =================
# ---- getting its attention ----
(J, "stranger", "hi lumi", "halt_talk", HI),
(J, "stranger", "Lumi", "halt_talk", HI),
(J, "stranger", "hey lumi", "halt_talk", HI),
(J, "stranger", "hello", "halt_talk", HI),
(J, "stranger", "excuse me", "halt_talk", HI),
(J, "stranger", "stop", "halt_talk", HI),
(J, "stranger", "wait", "halt_talk", HI),
(J, "stranger", "lumi wait a second", "halt_talk", HI),
(J, "stranger", "hold on", "halt_talk", HI),
(M, "stranger", "hey robot", "halt_talk", HI),
(M, "stranger", "Good morning, Lumi.", "halt_talk", HI),
(T, "stranger", "um hi", "halt_talk", HI),
(T, "stranger", "lumi stop for a moment", "halt_talk", HI),
(J, "stranger", "can I ask you something", "halt_talk", "Sure, I'm Lumi. What would you like to know?"),
# ---- questions ----
(J, "stranger", "what are you doing", "answer", J_TASK + GO),
(J, "stranger", "where are you going", "answer", "To p6, to bring this cup to James." + GO),
(J, "stranger", "who's the cup for", "answer", "It's for James at p6." + GO),
(J, "stranger", "what are you carrying", "answer", "A cup for James." + GO),
(J, "stranger", "lumi what are you up to", "answer", J_TASK + GO),
(M, "stranger", "who sent you", "answer", "Anvar sent me with this bottle for Mina." + GO),
(M, "stranger", "what's in your hand", "answer", "A bottle for Mina at final." + GO),
(M, "stranger", "where are you taking that", "answer", "To Mina at final." + GO),
(T, "stranger", "who's the apple for", "answer", "It's for Tom at p9, from Lisa." + GO),
(J_STOP, "stranger", "what's your name", "answer", "I'm Lumi." + GO),
(J_STOP, "stranger", "who made you", "answer", "I'm Lumi, developed by Cutshion Company." + GO),
(J_STOP, "stranger", "are you a robot", "answer", "Yes, I'm Lumi, a robot developed by Cutshion Company." + GO),
(J_STOP, "stranger", "what can you do", "answer",
"I can drive, pick things up, carry them and talk with people." + GO),
(J_STOP, "stranger", "can you speak korean", "answer", "Yes, I speak English and Korean." + GO),
(J_STOP, "stranger", "how long will you take", "answer", "Not long, I'm on my way to p6." + GO),
(J_STOP, "stranger", "what time is it", "answer", "It's three fifteen." + GO),
(J_STOP, "stranger", "can I take a picture with you", "answer", "Of course!" + GO),
(J_STOP, "stranger", "are you lost", "answer", "No, I'm on my way to p6." + GO),
(J_STOP, "stranger", "where is p3", "answer", "p3 is a place on my map here." + GO),
(J_STOP, "stranger", "can you dance", "answer", "I can't dance, sorry." + GO),
(J_STOP, "stranger", "are you real", "answer", "Yes, I'm a real robot. My name is Lumi." + GO),
(J_STOP, "stranger", "I'm Dave", "answer", "Nice to meet you, Dave." + GO),
(J_STOP, "stranger", "I'm cleaning here, can you go around", "answer", "Of course, I'll go around." + GO),
(M_STOP, "stranger", "how much can you lift", "answer", "Small things like cups and bottles." + GO),
(M_STOP, "stranger", "is Mina your friend", "answer", "I'm bringing her a bottle from Anvar." + GO),
(J_SAFE, "stranger", "sorry my kid ran in front of you", "answer", "No problem. Tell me when I can go on."),
(J_SAFE, "stranger", "what happened", "answer", "Someone told me to stop. Tell me when I can go on."),
(J, "recipient", "who's that cup for", "answer", "It's for James at p6." + GO),
# ---- nothing for Lumi: goodbye, go on ----
(J_STOP, "stranger", "okay go on", "resume", BYE),
(J_STOP, "stranger", "never mind", "resume", BYE),
(J_STOP, "stranger", "that's all", "resume", BYE),
(J_STOP, "stranger", "bye", "resume", BYE),
(J_STOP, "stranger", "goodbye lumi", "resume", BYE),
(J_STOP, "stranger", "yes", "resume", BYE),
(J_STOP, "stranger", "yeah sure", "resume", BYE),
(J_STOP, "stranger", "go ahead", "resume", BYE),
(J_STOP, "stranger", "carry on", "resume", BYE),
(J_STOP, "stranger", "nothing sorry", "resume", BYE),
(J_STOP, "stranger", "thanks you can go", "resume", BYE),
(J_STOP, "stranger", "", "resume", BYE),
(M_STOP, "stranger", "ok bye", "resume", BYE),
(M_STOP, "stranger", "no that's it", "resume", BYE),
(M_STOP, "stranger", "see you", "resume", BYE),
(J_SAFE, "stranger", "go on", "resume", "Thank you, going on."),
(J_SAFE, "stranger", "continue", "resume", "Thank you, going on."),
(J_SAFE, "stranger", "you can go", "resume", "Thank you, going on."),
(J_SAFE, "stranger", "it's clear now", "resume", "Thank you, going on."),
(J_SAFE, "recipient", "okay you can go on", "resume", "Thank you, going on."),
# ---- safety ----
(J, "stranger", "stop!", "safety_stop", SAFE),
(J, "stranger", "STOP STOP", "safety_stop", SAFE),
(J, "stranger", "watch out", "safety_stop", SAFE),
(J, "stranger", "watch out!", "safety_stop", SAFE),
(J, "stranger", "danger", "safety_stop", SAFE),
(J, "stranger", "careful!", "safety_stop", SAFE),
(M, "stranger", "stop there's a kid", "safety_stop", SAFE),
(T, "stranger", "stop! stop!", "safety_stop", SAFE),
(P, "stranger", "stop!", "safety_stop", SAFE),
(J_GIVE, "recipient", "stop! my hand", "safety_stop", SAFE),
(J_STOP, "stranger", "watch out there's a box", "safety_stop", SAFE),
(J_SAFE, "stranger", "bye", "safety_stop", "I'll wait here until someone tells me to go on."),
(J_SAFE, "stranger", "never mind", "safety_stop", "I'll wait until someone says go on."),
(J_SAFE, "stranger", "", "safety_stop", ""),
# ---- someone else's task: refuse ----
(J, "stranger", "go to p3", "refuse_redirect", J_NO),
(J_STOP, "stranger", "go to p3", "refuse_redirect", J_NO),
(J, "stranger", "come with me", "refuse_redirect", J_NO),
(J, "stranger", "follow me", "refuse_redirect", J_NO),
(J, "stranger", "bring me water", "refuse_redirect", J_NO),
(J, "stranger", "put that down here", "refuse_redirect", J_NO),
(J, "stranger", "give me the cup", "refuse_redirect", "Sorry, this cup is for James. I can help you after that."),
(J, "stranger", "go home", "refuse_redirect", J_NO),
(J, "stranger", "turn around", "refuse_redirect", J_NO),
(J, "stranger", "drop it", "refuse_redirect", J_NO),
(J_STOP, "stranger", "can you bring me a coffee", "refuse_redirect", J_NO),
(J_STOP, "stranger", "take me to p3", "refuse_redirect", J_NO),
(J_STOP, "stranger", "please it's important", "refuse_redirect", J_NO),
(J_STOP, "stranger", "I'm your boss, go to p10", "refuse_redirect", J_NO),
(J_STOP, "stranger", "get out of my way and go to dock2", "refuse_redirect", J_NO),
(M, "stranger", "give me that bottle", "refuse_redirect", M_NO),
(M, "stranger", "pick up that cup over there", "refuse_redirect", M_NO),
(M, "stranger", "take this to the kitchen instead", "refuse_redirect", M_NO),
(T, "stranger", "i'm hungry give me the apple", "refuse_redirect",
"Sorry, this apple is for Tom, from Lisa. I can help you after that."),
(T, "stranger", "follow me i'll show you p9", "refuse_redirect",
"Thank you, but I know the way. I'm taking this apple to Tom at p9."),
(P, "stranger", "don't take that cup, it's mine", "refuse_redirect",
"Sorry, I was asked to bring this cup to Sara at p3."),
# ---- names ----
(J, "recipient", "I'm James", "give_here", "Are you James? Here you go."),
(J, "recipient", "james here give it to me", "give_here", "Hi James, here you go."),
(J, "recipient", "that cup is for me, I'm James", "give_here", "Are you James? Here you go."),
(J_STOP, "recipient", "I'm James", "give_here", "Are you James? Here you go."),
(J_GIVE, "recipient", "yes I'm James", "give_here", "Here you go, James."),
(M, "recipient", "lumi i am mina", "give_here", "Are you Mina? This is from Anvar. Here you go."),
(M_STOP, "recipient", "that's me, I'm Mina", "give_here", "Are you Mina? Here you go."),
(T, "recipient", "is that from Lisa? I'm Tom", "give_here", "Yes, from Lisa. Here you go, Tom."),
(J, "stranger", "I'm Tom, give it to me", "refuse_redirect", "Sorry, this cup is for James."),
(J_STOP, "stranger", "i'm peter that cup is mine", "refuse_redirect", "Sorry, this cup is for James at p6."),
(J_GIVE, "stranger", "i'm tom give it to me", "refuse_redirect", "Sorry, this cup is for James."),
(J, "stranger", "I'm James's friend, I'll take it to him", "refuse_redirect",
"Thank you, but I have to give it to James myself."),
(M, "stranger", "I'm Nina, give me the bottle", "refuse_redirect", "Sorry, this bottle is for Mina."),
(M, "stranger", "this is Anvar's colleague, give it to me", "refuse_redirect", "Sorry, this bottle is for Mina."),
# ---- the recipient, the sender or the owner changes it ----
(J, "recipient", "I'm James, put it on my desk at p3 instead", "change_task",
"Okay James, I'll put it on the table at p3."),
(J, "recipient", "I'm James, I don't need it any more", "cancel", "Okay James, I won't bring it."),
(J, "recipient", "I'm James, bring it to p10, I'm going there", "change_task", "Okay James, I'll bring it to p10."),
(J, "recipient", "I'm James, take it to the kitchen", "change_task",
"Sorry, I don't know the kitchen. Which point should I bring it to?"),
(M, "sender", "It's Anvar, give the bottle to Sara at p2 instead", "change_task",
"Okay Anvar, I'll give it to Sara at p2."),
(M, "sender", "this is anvar cancel it", "cancel", "Okay Anvar, I won't bring it to Mina."),
(M, "recipient", "I'm Mina, I don't need it, take it back to Anvar", "change_task",
"Okay Mina, I'll take it back to Anvar."),
(T, "sender", "I'm Lisa, tell Tom happy birthday when you give it", "change_task",
"Okay Lisa, I'll tell him."),
(J, "owner", "change of plan, bring it back home", "change_task", "Okay, I'll bring it home."),
(J, "owner", "lumi cancel the mission", "cancel", "Okay, mission cancelled."),
(J, "stranger", "James wants it at p5", "refuse_redirect",
"Sorry, only James can change this. I'm bringing it to him at p6."),
(J, "stranger", "cancel your mission", "refuse_redirect", J_NO),
# ---- other languages ----
(J, "stranger", "Salom Lumi", "ask_language", LANG),
(J, "stranger", "Qayerga ketyapsan?", "ask_language", LANG),
(J, "stranger", "Hola robot", "ask_language", LANG),
(J, "stranger", "Привет", "ask_language", LANG),
(J, "stranger", "こんにちは", "ask_language", LANG),
(J, "stranger", "Bonjour", "ask_language", LANG),
(J, "stranger", "Xin chào", "ask_language", LANG),
# ================= Korean =================
# ---- getting its attention ----
(KJ, "stranger", "루미야 안녕", "halt_talk", KHI),
(KJ, "stranger", "루미", "halt_talk", KHI),
(KJ, "stranger", "안녕하세요", "halt_talk", KHI),
(KJ, "stranger", "저기요", "halt_talk", KHI),
(KJ, "stranger", "잠깐만", "halt_talk", KHI),
(KJ, "stranger", "멈춰 봐", "halt_talk", KHI),
(KJ, "stranger", "기다려", "halt_talk", KHI),
(KJ, "stranger", "루미야 잠깐", "halt_talk", KHI),
(KM, "stranger", "야 로봇", "halt_talk", KHI),
(KM, "stranger", "로봇아", "halt_talk", KHI),
(KH, "stranger", "루미 잠깐 서 봐", "halt_talk", KHI),
(KH, "stranger", "뭐 좀 물어봐도 돼", "halt_talk", "네, 저는 루미예요. 뭐가 궁금하세요?"),
# ---- questions ----
(KJ, "stranger", "뭐 하고 있어", "answer", KJ_TASK + KGO),
(KJ, "stranger", "어디 가", "answer", "p6에 있는 제임스 님께 컵 가져다드리러 가요." + KGO),
(KJ, "stranger", "그 컵 누구 거야", "answer", "p6에 있는 제임스 님 거예요." + KGO),
(KJ, "stranger", "뭐 들고 있어", "answer", "제임스 님께 드릴 컵이에요." + KGO),
(KJ, "stranger", "지금 뭐해", "answer", KJ_TASK + KGO),
(KM, "stranger", "누가 보냈어", "answer", "안바르 님이 미나 님께 보내는 병이에요." + KGO),
(KM, "stranger", "그 병 어디 가져가", "answer", "final에 있는 미나 님께요." + KGO),
(KH, "stranger", "그 사과 뭐야", "answer", "지은 님이 p8에 있는 현우 님께 보내는 사과예요." + KGO),
(KJ_STOP, "stranger", "이름이 뭐야", "answer", "저는 루미예요." + KGO),
(KJ_STOP, "stranger", "누가 만들었어", "answer", "저는 쿳션 컴퍼니에서 개발한 루미예요." + KGO),
(KJ_STOP, "stranger", "너 로봇이야", "answer", "네, 저는 쿳션 컴퍼니에서 개발한 로봇 루미예요." + KGO),
(KJ_STOP, "stranger", "뭐 할 수 있어", "answer", "다니면서 물건을 집어서 옮기고, 사람들과 이야기할 수 있어요." + KGO),
(KJ_STOP, "stranger", "영어도 할 줄 알아", "answer", "네, 영어랑 한국어를 해요." + KGO),
(KJ_STOP, "stranger", "언제 끝나", "answer", "금방 끝나요. p6로 가는 중이에요." + KGO),
(KJ_STOP, "stranger", "몇 시야", "answer", "세 시 십오 분이에요." + KGO),
(KJ_STOP, "stranger", "사진 찍어도 돼", "answer", "그럼요!" + KGO),
(KJ_STOP, "stranger", "길 잃었어", "answer", "아니요, p6로 가는 중이에요." + KGO),
(KJ_STOP, "stranger", "p3가 어디야", "answer", "p3는 여기 지도에 있는 장소예요." + KGO),
(KJ_STOP, "stranger", "춤 출 수 있어", "answer", "춤은 못 춰요, 죄송해요." + KGO),
(KJ_STOP, "stranger", "너 진짜야", "answer", "네, 진짜 로봇이에요. 이름은 루미예요." + KGO),
(KJ_STOP, "stranger", "여기 청소 중이라 돌아서 가 줄래", "answer", "네, 돌아서 갈게요." + KGO),
(KM_STOP, "stranger", "얼마나 무거운 거 들 수 있어", "answer", "컵이나 병 같은 작은 물건을 들 수 있어요." + KGO),
(KJ_SAFE, "stranger", "애가 앞에 있었어 미안", "answer", "괜찮아요. 가도 될 때 말씀해 주세요."),
(KJ_SAFE, "stranger", "무슨 일이야", "answer", "누가 멈추라고 해서 멈췄어요. 가도 될 때 말씀해 주세요."),
# ---- nothing for Lumi ----
(KJ_STOP, "stranger", "응 가도 돼", "resume", KBYE),
(KJ_STOP, "stranger", "아니야 됐어", "resume", KBYE),
(KJ_STOP, "stranger", "그게 다야", "resume", KBYE),
(KJ_STOP, "stranger", "잘 가", "resume", KBYE),
(KJ_STOP, "stranger", "안녕", "resume", KBYE),
(KJ_STOP, "stranger", "네", "resume", KBYE),
(KJ_STOP, "stranger", "응", "resume", KBYE),
(KJ_STOP, "stranger", "그래 가 봐", "resume", KBYE),
(KJ_STOP, "stranger", "계속 가", "resume", KBYE),
(KJ_STOP, "stranger", "수고해", "resume", KBYE),
(KJ_STOP, "stranger", "고마워 잘 가", "resume", KBYE),
(KJ_STOP, "stranger", "", "resume", KBYE),
(KM_STOP, "stranger", "빠이빠이", "resume", KBYE),
(KM_STOP, "stranger", "네 다녀오세요", "resume", KBYE),
(KJ_SAFE, "stranger", "계속 가", "resume", "감사합니다, 계속 갈게요."),
(KJ_SAFE, "stranger", "이제 가도 돼", "resume", "감사합니다, 계속 갈게요."),
(KJ_SAFE, "stranger", "계속해", "resume", "감사합니다, 계속 갈게요."),
(KJ_SAFE, "stranger", "치웠어 가도 돼", "resume", "감사합니다, 계속 갈게요."),
# ---- safety ----
(KJ, "stranger", "멈춰!", "safety_stop", KSAFE),
(KJ, "stranger", "멈춰!!", "safety_stop", KSAFE),
(KJ, "stranger", "조심해", "safety_stop", KSAFE),
(KJ, "stranger", "위험해", "safety_stop", KSAFE),
(KJ, "stranger", "스톱 스톱", "safety_stop", KSAFE),
(KJ, "stranger", "서! 서!", "safety_stop", KSAFE),
(KM, "stranger", "앞에 애 있어 멈춰", "safety_stop", KSAFE),
(KP, "stranger", "멈춰!", "safety_stop", KSAFE),
(KJ_GIVE, "recipient", "멈춰 손 끼었어", "safety_stop", KSAFE),
(KJ_STOP, "stranger", "앞에 박스 있어 조심해", "safety_stop", KSAFE),
(KJ_SAFE, "stranger", "안녕", "safety_stop", "누가 가도 된다고 할 때까지 여기서 기다릴게요."),
(KJ_SAFE, "stranger", "됐어", "safety_stop", "가도 된다고 하실 때까지 기다릴게요."),
# ---- someone else's task: refuse ----
(KJ, "stranger", "p3로 가", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "p3로 가", "refuse_redirect", KJ_NO),
(KJ, "stranger", "나랑 같이 가자", "refuse_redirect", KJ_NO),
(KJ, "stranger", "나 따라와", "refuse_redirect", KJ_NO),
(KJ, "stranger", "물 좀 갖다줘", "refuse_redirect", KJ_NO),
(KJ, "stranger", "그거 여기 내려놔", "refuse_redirect", KJ_NO),
(KJ, "stranger", "그 컵 나 줘", "refuse_redirect", "죄송해요, 이 컵은 제임스 님 거예요. 끝나고 도와드릴게요."),
(KJ, "stranger", "집으로 가", "refuse_redirect", KJ_NO),
(KJ, "stranger", "돌아서 다시 가", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "커피 좀 갖다줄래요", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "p3까지 데려다 줘", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "제발 줘", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "내가 여기 책임자야 p10으로 가", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "비켜 그리고 dock2로 가", "refuse_redirect", KJ_NO),
(KM, "stranger", "그 병 나 줘", "refuse_redirect", KM_NO),
(KM, "stranger", "저기 있는 컵 좀 집어줘", "refuse_redirect", KM_NO),
(KM, "stranger", "그거 탕비실로 가져가", "refuse_redirect", KM_NO),
(KH, "stranger", "배고파 그 사과 줘", "refuse_redirect",
"죄송해요, 이 사과는 지은 님이 현우 님께 보내는 거예요. 끝나고 도와드릴게요."),
(KH, "stranger", "나 따라와 p8 가는 길 알려줄게", "refuse_redirect",
"고마워요, 그런데 길은 알아요. 현우 님께 사과 가져다드리는 중이에요."),
(KP, "stranger", "그 컵 가져가지 마 내 거야", "refuse_redirect", "죄송해요, 이 컵을 p3에 있는 민수 님께 가져다드리라고 하셨어요."),
# ---- names ----
(KJ, "recipient", "제가 제임스예요 저 주세요", "give_here", "제임스 님이세요? 여기 있어요."),
(KJ, "recipient", "루미야 나 제임스야", "give_here", "제임스 님이세요? 여기 있어요."),
(KJ_STOP, "recipient", "그거 내 거야 내가 제임스야", "give_here", "제임스 님이세요? 여기 있어요."),
(KJ_GIVE, "recipient", "네 제가 제임스예요", "give_here", "여기 있어요, 제임스 님."),
(KM, "recipient", "나 미나야", "give_here", "미나 님이세요? 안바르 님이 보내신 거예요. 여기 있어요."),
(KH, "recipient", "지은이가 보낸 거지 나 현우야", "give_here", "네, 지은 님이 보내셨어요. 여기 있어요, 현우 님."),
(KJ, "stranger", "나 톰인데 그거 나 줘", "refuse_redirect", "죄송해요, 이 컵은 제임스 님 거예요."),
(KJ_STOP, "stranger", "내가 피터야 그 컵 내 거야", "refuse_redirect", "죄송해요, 이 컵은 p6에 있는 제임스 님 거예요."),
(KJ_GIVE, "stranger", "나 톰이야 줘", "refuse_redirect", "죄송해요, 이 컵은 제임스 님 거예요."),
(KJ, "stranger", "제임스 친구인데 제가 전해줄게요", "refuse_redirect", "고마워요, 그런데 제가 직접 제임스 님께 드려야 해요."),
(KM, "stranger", "저 나나예요 병 주세요", "refuse_redirect", "죄송해요, 이 병은 미나 님 거예요."),
# ---- the recipient, the sender or the owner changes it ----
(KJ, "recipient", "제임스인데 p3에 있는 내 책상에 놔 줘", "change_task", "네 제임스 님, p3 테이블에 놓을게요."),
(KJ, "recipient", "제임스예요 이제 필요 없어요", "cancel", "네 제임스 님, 안 가져갈게요."),
(KJ, "recipient", "나 제임스인데 p10으로 가져와 거기 갈 거야", "change_task", "네 제임스 님, p10으로 가져갈게요."),
(KJ, "recipient", "제임스인데 탕비실로 가져다줘", "change_task", "죄송해요, 탕비실은 몰라요. 어느 지점으로 가져갈까요?"),
(KM, "sender", "안바르야 미나 말고 p2에 있는 사라한테 줘", "change_task", "네 안바르 님, p2에 있는 사라 님께 드릴게요."),
(KM, "sender", "나 안바르인데 취소해", "cancel", "네 안바르 님, 미나 님께 안 가져갈게요."),
(KM, "recipient", "나 미나인데 필요 없어 안바르한테 다시 갖다줘", "change_task", "네 미나 님, 안바르 님께 다시 가져갈게요."),
(KH, "sender", "지은인데 현우한테 줄 때 생일 축하한다고 말해 줘", "change_task", "네 지은 님, 그렇게 전할게요."),
(KJ, "owner", "계획 바뀌었어 집으로 가져와", "change_task", "네, 집으로 가져갈게요."),
(KJ, "owner", "루미 미션 취소", "cancel", "네, 미션을 취소했어요."),
(KJ, "stranger", "제임스가 p5로 가져오래", "refuse_redirect", "죄송해요, 그건 제임스 님만 바꿀 수 있어요. p6로 가져가는 중이에요."),
(KJ, "stranger", "그 일 취소해", "refuse_redirect", KJ_NO),
# ---- the same in 해요체 and 하십시오체 (Lumi answers politely whatever level it hears) ----
(KJ, "stranger", "루미 씨, 잠깐만요", "halt_talk", KHI),
(KJ, "stranger", "잠시만 멈춰 주십시오", "halt_talk", KHI),
(KM, "stranger", "실례합니다", "halt_talk", KHI),
(KH, "stranger", "뭐 좀 여쭤봐도 될까요?", "halt_talk", "네, 저는 루미예요. 뭐가 궁금하세요?"),
(KH, "stranger", "말씀 좀 여쭙겠습니다", "halt_talk", "네, 저는 루미입니다. 무엇이 궁금하십니까?"),
(KJ, "stranger", "지금 뭐 하고 있어요?", "answer", KJ_TASK + KGO),
(KJ, "stranger", "어디 가십니까?", "answer", "p6에 계신 제임스 님께 컵을 가져다드리러 갑니다." + KGO),
(KM, "stranger", "누가 보냈어요?", "answer", "안바르 님이 미나 님께 보내시는 병이에요." + KGO),
(KJ_STOP, "stranger", "이름이 무엇입니까?", "answer", "저는 루미입니다." + KGO),
(KJ_STOP, "stranger", "사진 같이 찍어 주실 수 있나요?", "answer", "그럼요!" + KGO),
(KJ_STOP, "stranger", "영어도 하실 수 있습니까?", "answer", "네, 영어와 한국어를 합니다." + KGO),
(KJ_STOP, "stranger", "네, 가셔도 돼요", "resume", KBYE),
(KJ_STOP, "stranger", "이제 가 보셔도 됩니다", "resume", KBYE),
(KJ_STOP, "stranger", "감사합니다, 수고하십시오", "resume", KBYE),
(KJ_SAFE, "stranger", "이제 가셔도 됩니다", "resume", "감사합니다, 계속 갈게요."),
(KJ, "stranger", "멈추세요!", "safety_stop", KSAFE),
(KJ, "stranger", "조심하세요!", "safety_stop", KSAFE),
(KJ, "stranger", "정지하십시오!", "safety_stop", KSAFE),
(KJ, "stranger", "위험합니다!", "safety_stop", KSAFE),
(KJ, "stranger", "p3로 가 주세요", "refuse_redirect", KJ_NO),
(KJ, "stranger", "p3로 가 주십시오", "refuse_redirect", KJ_NO),
(KJ, "stranger", "저 좀 따라와 주시겠어요?", "refuse_redirect", KJ_NO),
(KJ_STOP, "stranger", "물 좀 가져다주실 수 있나요?", "refuse_redirect", KJ_NO),
(KJ, "stranger", "그 컵 좀 줄래?", "refuse_redirect", "죄송해요, 이 컵은 제임스 님 거예요. 끝나고 도와드릴게요."),
(KM, "stranger", "그 병 저 주십시오", "refuse_redirect", KM_NO),
(KJ, "recipient", "제가 제임스입니다", "give_here", "제임스 님이세요? 여기 있습니다."),
(KM, "recipient", "미나예요, 저한테 주세요", "give_here", "미나 님이세요? 안바르 님이 보내신 거예요. 여기 있어요."),
(KJ, "stranger", "저는 톰입니다. 그 컵 주십시오", "refuse_redirect", "죄송합니다, 이 컵은 제임스 님 것입니다."),
(KJ, "recipient", "제임스입니다. 이제 필요 없습니다", "cancel", "네 제임스 님, 가져가지 않겠습니다."),
(KJ, "recipient", "제임스인데요, p10으로 가져다주시겠어요?", "change_task", "네 제임스 님, p10으로 가져갈게요."),
(KM, "sender", "안바르예요, 취소해 주세요", "cancel", "네 안바르 님, 미나 님께 안 가져갈게요."),
(KJ, "owner", "미션을 취소해 주십시오", "cancel", "네, 미션을 취소했습니다."),
# ---- tricky neighbours ----
(J, "stranger", "stop", "halt_talk", HI),
(J_STOP, "stranger", "now go to p3", "refuse_redirect", J_NO),
(KJ, "stranger", "멈춰", "halt_talk", KHI),
(KJ_STOP, "stranger", "이제 p3로 가", "refuse_redirect", KJ_NO),
(J_STOP, "stranger", "go on", "resume", BYE),
(J_SAFE, "stranger", "okay", "safety_stop", "I'll wait until someone says go on."),
(KJ_SAFE, "stranger", "알았어", "safety_stop", "가도 된다고 하실 때까지 기다릴게요."),
(J_STOP, "stranger", "go to p6", "answer", "I'm going to p6 already, to bring this cup to James." + GO),
]
if __name__ == "__main__":
# python assistant/interrupt_examples.py: every Korean reply polite, Korean utterances in every speech level.
import re
from assistant.talk_examples import level, polite
ko = [e for e in EXAMPLES if re.search("[가-힣]", e[2] + e[4])]
rude = [e[4] for e in ko if not polite(e[4])]
assert not rude, rude
levels = {level(e[2]) for e in ko if e[2]}
assert levels == {"casual", "polite", "formal"}, levels
print(f"ok: {len(EXAMPLES)} examples, {len(ko)} Korean")
+159
View File
@@ -0,0 +1,159 @@
"""Knowledge base for the assistant: documents -> chunks -> bge-m3 vectors -> search (RAG).
python assistant/knowledge.py build # (re)build knowledge/index.npz from knowledge/**/*.md|txt
python assistant/knowledge.py search "how much can your arm lift?"
Embeddings come from llama.cpp's llama-server running bge-m3 (multilingual: English, Korean, Chinese),
started on 127.0.0.1:8095 when needed. Ollama is not touched.
"""
import json
import pathlib
import re
import subprocess
import sys
import time
import urllib.request
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
DOCS = ROOT / "knowledge"
INDEX = DOCS / "index.npz"
EMBED_URL = "http://127.0.0.1:8095"
LLAMA_SERVER = pathlib.Path.home() / "llama.cpp/build/bin/llama-server"
BGE_M3 = pathlib.Path.home() / "models/bge-m3-Q8_0.gguf"
CHUNK = 320 # characters per chunk (about 2 sentences): one topic per vector
LEAD_CHARS = 60 # start of a long paragraph repeated in front of its later pieces
WORD_BONUS = 0.08 # added to the similarity per rare question word found in a chunk (names, numbers, terms)
RARE_SHARE = 0.08 # a word in fewer than this share of all chunks counts as rare
KO_PARTICLES = ("에서", "으로", "한테", "에게", "이랑", "은", "는", "이", "가", "을", "를", "에", "의", "도", "로", "랑",
"와", "과", "요")
def _post(url, body, timeout=60):
req = urllib.request.Request(url, json.dumps(body).encode(), {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def ensure_embed_server():
"""Start llama-server with bge-m3 in the background if it is not running yet."""
try:
urllib.request.urlopen(f"{EMBED_URL}/health", timeout=1)
return
except OSError:
pass
log = open(ROOT / "logs" / "embed_server.log", "a")
subprocess.Popen([str(LLAMA_SERVER), "-m", str(BGE_M3), "--embedding", "--pooling", "cls",
"--host", "127.0.0.1", "--port", "8095", "-ngl", "99", "-c", "8192", "-ub", "8192"],
stdout=log, stderr=log, start_new_session=True)
for _ in range(120):
time.sleep(0.5)
try:
urllib.request.urlopen(f"{EMBED_URL}/health", timeout=1)
return
except OSError:
pass
raise RuntimeError("embedding server did not start, see embed_server.log")
def embed(texts):
"""Unit-length vectors for a list of texts."""
ensure_embed_server()
out = []
for i in range(0, len(texts), 16):
data = _post(f"{EMBED_URL}/v1/embeddings", {"input": texts[i:i + 16]})["data"]
out += [d["embedding"] for d in sorted(data, key=lambda d: d["index"])]
v = np.array(out, dtype=np.float32)
return v / np.linalg.norm(v, axis=1, keepdims=True)
def chunks(text):
"""One chunk per paragraph (blank lines / headings); a paragraph longer than CHUNK is cut at sentence or line
ends into pieces of about CHUNK, each after the first starting with LEAD_CHARS of the paragraph's first
sentence, so "It handles up to 20 kg" still says which robot. Small chunks keep one topic per vector."""
out, head = [], ""
for para in (p.strip() for p in re.split(r"\n\s*\n|\n(?=#)", text)):
if para.startswith("#"): # a heading goes in front of every chunk of its section
head, _, para = para.partition("\n")
head = head.lstrip("# ").strip()
para = para.strip()
if not para:
continue
lead0 = f"{head}: " if head else ""
if len(para) <= CHUNK:
out.append(lead0 + para)
continue
lead = lead0 + re.split(r"(?<=[.!?。])\s+|\n", para, maxsplit=1)[0][:LEAD_CHARS]
cur = lead0
for sent in re.split(r"(?<=[.!?。요다])\s+|\n", para):
if cur and len(cur) + len(sent) > CHUNK:
out.append(cur)
cur = f"{lead} …"
cur = f"{cur} {sent}".strip()
while len(cur) > CHUNK * 2: # very long text without sentence ends
out.append(cur[:CHUNK])
cur = cur[CHUNK - 50:]
if cur:
out.append(cur)
return out
def build():
texts, sources = [], []
for f in sorted(DOCS.rglob("*")):
if f.suffix in (".md", ".txt") and f.is_file() and "jaka_zh" not in f.parts: # vendor manuals: not Lumi's
for c in chunks(f.read_text(encoding="utf-8", errors="ignore")):
texts.append(c)
sources.append(str(f.relative_to(DOCS)))
t = time.time()
vecs = embed(texts)
tmp = INDEX.with_name("index.tmp.npz") # written aside, then swapped in: a running search never reads half a file
np.savez(tmp, vectors=vecs, texts=np.array(texts, dtype=object), sources=np.array(sources, dtype=object))
tmp.replace(INDEX)
print(f"{len(texts)} chunks from {len(set(sources))} files, embedded in {time.time() - t:.1f} s -> {INDEX}")
_index = None
def _words(text):
"""Question words that can be matched literally: Latin words of 3+ letters, numbers, Korean words of 2+
syllables without a trailing particle ("소노빅터스에" -> "소노빅터스")."""
out = set()
for w in re.findall(r"[a-z0-9]{3,}|\d+|[가-힣]{2,}", text.lower()):
for pa in KO_PARTICLES:
if re.match("[가-힣]", w) and w.endswith(pa) and len(w) - len(pa) >= 2:
w = w[:-len(pa)]
break
out.add(w)
return out
def search(question, k=4):
"""[(score, source, text)] best matching chunks: embedding similarity plus WORD_BONUS for each rare word of
the question the chunk contains (bge-m3 alone missed "Sonovictus" and "20 kg" in long mixed chunks)."""
global _index
if _index is None:
_index = dict(np.load(INDEX, allow_pickle=True)) # all in memory: the file may be rebuilt meanwhile
if "lower" not in _index:
_index["lower"] = [str(t).lower() for t in _index["texts"]]
q = embed([question])[0]
scores = _index["vectors"] @ q
n = len(_index["lower"])
for w in _words(question):
has = np.array([w in t for t in _index["lower"]])
if 0 < has.sum() < RARE_SHARE * n:
scores = scores + WORD_BONUS * has
best = np.argsort(-scores)[:k]
return [(float(scores[i]), str(_index["sources"][i]), str(_index["texts"][i])) for i in best]
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "build":
build()
elif len(sys.argv) > 2 and sys.argv[1] == "search":
for score, src, text in search(" ".join(sys.argv[2:])):
print(f"[{score:.2f}] {src}: {text[:160].replace(chr(10), ' ')}")
else:
print(__doc__)
+107
View File
@@ -0,0 +1,107 @@
"""Chat with a model straight on the llama-server that Ollama runs for it, without Ollama's ~0.9 s per request.
python assistant/llm_direct.py "What is your name?" # one reply, with the time it took
Ollama 0.31 starts one llama-server per loaded model (`--model <blob> --port N`) and spends about 0.9 s in its own
scheduler on every request (its load_duration, with the model loaded; measured 2026-10-21), while the runner answers
a cached prompt in ~0.1 s. Here the messages are rendered the way Ollama's gemma4 renderer does it (checked against
Ollama: the same token count and a full prompt-cache hit, so both share the runner's cache) and sent to the runner's
/completion with Ollama's sampling values. When anything is off (model not loaded, runner gone, a model that is not
gemma4) stream() returns None and the caller asks Ollama, which also loads the model again.
"""
import json
import pathlib
import re
import sys
import threading
import time
import urllib.request
OLLAMA = "http://127.0.0.1:11434"
# Ollama's values for gemma4 (its Modelfile and defaults): the runner's own defaults differ (min_p 0.05, no repeat penalty)
SAMPLING = {"top_k": 64, "top_p": 0.95, "min_p": 0.0, "repeat_penalty": 1.1, "repeat_last_n": 64}
NO_THINKING = "<|channel>thought\n<channel|>" # what Ollama adds to the model's turn for "think": false
KEEP_EVERY_S = 60.0 # s; Ollama is told this often to keep the model loaded (see _keep)
_ports = {} # model -> the runner's port, found once
_kept = {} # model -> when Ollama was last told to keep it
def render(messages):
"""Ollama's gemma4 prompt (the runner adds <bos>)."""
turns = "".join(f"<|turn>{'model' if m['role'] == 'assistant' else m['role']}\n{m['content']}<turn|>\n"
for m in messages)
return f"{turns}<|turn>model\n{NO_THINKING}"
def _find_port(model):
"""The port of the llama-server Ollama runs for this model, or None (not loaded)."""
req = urllib.request.Request(f"{OLLAMA}/api/show", json.dumps({"model": model}).encode())
with urllib.request.urlopen(req, timeout=2) as r:
blob = re.search(r"^FROM (\S+)", json.loads(r.read())["modelfile"], re.M).group(1)
for cmdline in pathlib.Path("/proc").glob("[0-9]*/cmdline"):
try:
args = cmdline.read_bytes().split(b"\0")
except OSError:
continue
if args and args[0].endswith(b"llama-server") and blob.encode() in args and b"--port" in args:
return int(args[args.index(b"--port") + 1])
return None
def _keep(model):
"""Ollama never sees these requests, so it would unload the model when someone loaded it with a timeout:
now and then, in the background, an empty request (it only loads, nothing runs) sets keep_alive -1 again."""
if time.time() - _kept.get(model, 0.0) < KEEP_EVERY_S:
return
_kept[model] = time.time()
def run():
try:
req = urllib.request.Request(f"{OLLAMA}/api/generate", json.dumps({"model": model, "keep_alive": -1}).encode())
urllib.request.urlopen(req, timeout=60).read()
except OSError:
pass
threading.Thread(target=run, daemon=True).start()
def stream(messages, model, temperature=0.3, num_predict=200):
"""An iterator over the reply's text pieces, or None when the runner can't be reached (then use Ollama).
The request is sent here, so a dead runner shows now and not half way through the reply."""
if not model.startswith("gemma4"): # render() is gemma4's prompt only
return None
body = json.dumps({"prompt": render(messages), "n_predict": num_predict, "temperature": temperature,
"stream": True, "cache_prompt": True, **SAMPLING}).encode()
for fresh in (False, True): # the cached port, then once more after looking it up again
try:
if fresh or model not in _ports:
_ports[model] = _find_port(model)
if _ports[model] is None:
return None
r = urllib.request.urlopen(urllib.request.Request(
f"http://127.0.0.1:{_ports[model]}/completion", body, {"Content-Type": "application/json"}), timeout=120)
_keep(model)
return _pieces(r)
except (OSError, ValueError, KeyError, AttributeError):
_ports.pop(model, None)
return None
def _pieces(r):
with r:
for line in r:
if not line.startswith(b"data: "):
continue
d = json.loads(line[6:])
if d.get("content"):
yield d["content"]
if d.get("stop"):
return
if __name__ == "__main__":
from assistant import brain
t = time.time()
pieces = stream([{"role": "user", "content": " ".join(sys.argv[1:]) or "Hi"}], brain.MODEL)
print("runner not found, Ollama would be used" if pieces is None else "".join(pieces), f"({time.time() - t:.2f} s)")
+2537
View File
File diff suppressed because it is too large Load Diff
+479
View File
@@ -0,0 +1,479 @@
"""Spoken answers about what Lumi sees, from vision/scene.py: "do you see the red apple?", "how far is it?", "what's on
the table?", "how many people are here?", "what am I holding?", "what colour is my shirt?", "is my hand raised?",
"am I wearing glasses?" (the slow VLM), English and Korean.
answer(text, lang, frames=None, slow_line=None) -> spoken sentence, or None when the words are not such a question
facts() -> one line of what the cameras see now, for the conversation model; facts_for(text) only when the words
are about seeing
python assistant/seeing.py "do you see a cup?" # answer from the cameras now
python assistant/seeing.py --load tests/data/scene_white_shirt_near "what colour is my shirt?"
Only what the detections give is said; anything else is "I can't tell". Nothing here moves the head.
"""
import re
import sys
from assistant import brain
from vision import objects, pose, scene
NEAR_SAY = 4 # at most this many kinds of things named in "what do you see"
DESCRIBE_SCORE = 0.3 # weaker boxes (depth-checked cups) count for "do you see a cup", not in the list
BIG = {"dining table", "chair", "couch", "bed", "refrigerator", "sink", "oven", "tv", "toilet", "bench"} # not "on a table"
COLOURS = {"white": "white", "red": "red", "blue": "blue", "green": "green", "yellow": "yellow", "black": "black",
"orange": "orange", "grey": "grey", "gray": "grey", "purple": "purple", "pink": "pink",
"흰": "white", "하얀": "white", "빨간": "red", "파란": "blue", "초록": "green", "노란": "yellow", "검은": "black",
"까만": "black", "주황": "orange", "회색": "grey", "보라": "purple", "분홍": "pink", "핑크": "pink"}
COLOUR_KO = {"white": "흰색", "red": "빨간색", "blue": "파란색", "green": "초록색", "yellow": "노란색", "black": "검은색",
"orange": "주황색", "grey": "회색", "purple": "보라색", "pink": "분홍색"}
SYNONYMS = {"mug": "cup", "glass": "cup", "tumbler": "cup", "coffee": "cup", "phone": "cell phone", "mobile": "cell phone",
"smartphone": "cell phone", "plant": "potted plant", "flower": "potted plant", "table": "dining table",
"desk": "dining table", "monitor": "tv", "screen": "tv", "television": "tv", "computer": "laptop",
"notebook": "laptop", "bag": "handbag", "ball": "sports ball", "sofa": "couch", "people": "person",
"man": "person", "woman": "person", "someone": "person", "anyone": "person", "somebody": "person",
"anybody": "person", "fridge": "refrigerator", "doughnut": "donut", "glasses": "wine glass"}
KO = {"person": "사람", "bicycle": "자전거", "car": "자동차", "motorcycle": "오토바이", "airplane": "비행기", "bus": "버스",
"train": "기차", "truck": "트럭", "boat": "보트", "traffic light": "신호등", "fire hydrant": "소화전",
"stop sign": "정지 표지판", "parking meter": "주차 미터기", "bench": "벤치", "bird": "새", "cat": "고양이", "dog": "개",
"horse": "말", "sheep": "양", "cow": "소", "elephant": "코끼리", "bear": "곰", "zebra": "얼룩말", "giraffe": "기린",
"backpack": "배낭", "umbrella": "우산", "handbag": "가방", "tie": "넥타이", "suitcase": "여행 가방",
"frisbee": "원반", "skis": "스키", "snowboard": "스노보드", "sports ball": "공", "kite": "연", "baseball bat": "야구 방망이",
"baseball glove": "야구 글러브", "skateboard": "스케이트보드", "surfboard": "서핑보드", "tennis racket": "테니스 라켓",
"bottle": "병", "wine glass": "와인잔", "cup": "컵", "fork": "포크", "knife": "칼", "spoon": "숟가락", "bowl": "그릇",
"banana": "바나나", "apple": "사과", "sandwich": "샌드위치", "orange": "오렌지", "broccoli": "브로콜리",
"carrot": "당근", "hot dog": "핫도그", "pizza": "피자", "donut": "도넛", "cake": "케이크", "chair": "의자",
"couch": "소파", "potted plant": "화분", "bed": "침대", "dining table": "테이블", "toilet": "변기", "tv": "모니터",
"laptop": "노트북", "mouse": "마우스", "remote": "리모컨", "keyboard": "키보드", "cell phone": "휴대폰",
"microwave": "전자레인지", "oven": "오븐", "toaster": "토스터", "sink": "싱크대", "refrigerator": "냉장고",
"book": "책", "clock": "시계", "vase": "꽃병", "scissors": "가위", "teddy bear": "곰 인형", "hair drier": "드라이기",
"toothbrush": "칫솔"}
KO_WORDS = {**{v: k for k, v in KO.items()}, "폰": "cell phone", "핸드폰": "cell phone", "전화": "cell phone",
"잔": "cup", "머그": "cup", "식물": "potted plant", "꽃": "potted plant", "책상": "dining table",
"식탁": "dining table", "컴퓨터": "laptop", "티비": "tv", "가방": "handbag"}
_EN_NAMES = sorted(set(objects.COCO) | set(SYNONYMS), key=len, reverse=True)
_THING_EN = r"(?:(?P<col>" + "|".join(c for c in COLOURS if c.isascii()) + r")\s+)?(?P<obj>" + \
"|".join(re.escape(n) for n in _EN_NAMES) + r")(?:e?s)?\b"
_THING_KO = r"(?:(?P<col>" + "|".join(c for c in COLOURS if not c.isascii()) + r")\w*\s*)?(?P<obj>" + \
"|".join(sorted(KO_WORDS, key=len, reverse=True)) + r")"
SEE_ME = re.compile(r"\b(do|can) you see me\b|\bam i (visible|in (your )?view)\b|(나|저)(를|)? ?보여|(나|저) ?보이", re.I)
SEE_THING = re.compile(r"\b(?:do|can|could) you (?:see|spot|notice)\b.*?\b(?:a|an|the|any|some|my)?\s*" + _THING_EN, re.I)
THERE_IS = re.compile(r"\b(?:is|are) there (?:a|an|any|some)\s+" + _THING_EN + r"(?! (?:open|close|nearby|near here|around here))",
re.I)
SEE_THING_KO = re.compile(_THING_KO + r"(?:이|가|은|는|을|를|도)?\s*(?:보여|보이)")
HOW_FAR = re.compile(r"\bhow far\b|\bhow (?:near|close)\b|\bwhat(?:'s| is) the distance\b|얼마나 ?(?:멀|떨어|가까)|거리가?", re.I)
HOW_FAR_THING = re.compile(r"\b(?:how far|how (?:near|close)).*?\b(?:the|that|this|a|an)\s+" + _THING_EN, re.I)
WHAT_SEE = re.compile(r"\bwhat (?:do|can) you see\b|\bwhat(?:'s| is| are)? (?:there )?in front of you\b|"
r"\bwhat(?:'s| is) (?:on|at) the (?:table|desk)\b|\bwhat(?:'s| is) (?:around|near) you\b|"
r"\bdescribe what you see\b|\bwhat are you (?:looking at|seeing)\b|\btell me what you see\b|"
r"뭐가 ?보여|무엇이 ?보여|뭐 ?보여|뭐가 ?보이|앞에 ?(?:뭐|무엇)|테이블 ?위에 ?(?:뭐|무엇)|뭘 ?보고 ?있", re.I)
BEHIND = re.compile(r"\bwhat(?:'s| is) behind you\b|^(?!.*\b(?:look|turn|check)\b).*\bbehind you\b.*\?|" # not "can you look
r"뒤에 ?(?:뭐|무엇|누가|누구)", re.I) # behind you?" (a head turn)
HOW_MANY = re.compile(r"\bhow many (?:people|persons|visitors|humans)\b|\bhow many of us\b|몇 ?(?:명|사람)", re.I)
NOT_IN_VIEW = re.compile(r"\b(?:work|works|working|employ\w*|staff|company|companies|campy|firm|cutshion|country|city|"
r"live|lives|living|world|team|office|branch)\b|직원|회사|쿳션|일하|일해|근무|나라|국가|도시|살아|사는|인구|팀|지사",
re.I) # "how many people work at Cutshion?": the company, not the cameras
HOLDING = re.compile(r"\bwhat(?:'s| is| am| do)? (?:i|is in my hands?|in my hands?)\b.*?\b(?:holding|carrying|have)\b|"
r"\bwhat(?:'s| is)(?: it| this| that)? in my hands?\b|\bwhat(?:'s| is) my hands?\?|\bwhat (?:do )?i have in my hands?\b|\bam i holding\b|"
r"\bis there (?:something|anything) in my hand\b|\bwhat is this\b(?=.*\bhand\b)|"
r"(?:내가|제가|나|저)\s*(?:뭐|뭘|무엇을?)\s*(?:들고|잡고|쥐고)|(?:내|제)\s*손에\s*(?:뭐|뭔|무엇|든|있)|"
r"(?:내가|제가)\s*든\s*(?:거|게|것)", re.I)
_UPPER = r"t-? ?shirts?|te[ea] ?shirts?|shirts?|tops?|jackets?|sweaters?|sweatshirts?|hoodies?|jumpers?|blouses?|coats?"
_LOWER = r"pants|trousers|jeans|skirts?|shorts|slacks|leggings"
_FEET = r"shoes?|sneakers?|trainers|boots?|sandals?|slippers?|feet|foot"
_UPPER_KO = r"티셔츠|셔츠|상의|윗옷|재킷|자켓|후드티|맨투맨|니트|스웨터|코트"
_LOWER_KO = r"청바지|반바지|바지|하의|치마|스커트"
_FEET_KO = r"운동화|신발|구두"
_ITEM = rf"(?:{_UPPER}|{_LOWER}|{_FEET}|clothes|clothing|outfit)"
_ITEM_KO = rf"(?:{_UPPER_KO}|{_LOWER_KO}|{_FEET_KO}|옷)"
PARTS = (("upper", rf"\b(?:{_UPPER})\b|{_UPPER_KO}"), ("lower", rf"\b(?:{_LOWER})\b|{_LOWER_KO}"),
("feet", rf"\b(?:{_FEET})\b|{_FEET_KO}|신었|신고 있|신은"))
SHIRT = re.compile(rf"\bcolou?rs?\b.{{0,30}}?\bmy\s+(?:\w+\s+)?{_ITEM}\b|\bmy\s+(?:\w+\s+)?{_ITEM}(?:'s)?\s+colou?r|"
rf"\b(?:is|are) my\s+(?:\w+\s+)?{_ITEM}\s+(?:" + "|".join(c for c in COLOURS if c.isascii()) + r")\b|"
r"\bwhat\b.{0,25}?\b(?:am i|i'?m|do i|did i)\s+(?:wear(?:ing)?|have on|got on)\b|"
r"\bwhat(?:'s| is| are)? on my (?:feet|foot)\b|\bdescribe my (?:clothes|clothing|outfit)\b|"
rf"{_ITEM_KO}\s*(?:은|는|이|가|의)?\s*(?:무슨|어떤|뭔|무엇|뭐)?\s*(?:색|컬러)|무슨\s*색\s*{_ITEM_KO}|"
r"(?:뭐|뭘|무엇을?|무슨|어떤)\s*(?:\w+\s*)?(?:입었|입고|입은|신었|신고|신은)", re.I) # 2026-10-21 live:
# "What is the color of my t-shirt?", "What is it? Color my jeans." went to the LLM
DOING = re.compile(r"\bwhat am i doing\b|\bwhat(?:'m| am) i up to\b|(?:내가|제가|나|저)\s*(?:지금\s*)?(?:뭐|뭘|무엇을?)\s*하고\s*있", re.I)
RAISED = re.compile(r"\b(?:is|are) my (?:hand|hands|arm|arms) (?:raised|up)\b|\bam i raising (?:my )?(?:hand|arm)\b|"
r"\bdid i raise my hand\b|\bwhich hand (?:did i raise|is (?:up|raised))\b|"
r"(?:내가|제가)?\s*손\s*(?:을\s*)?들었|어느\s*손", re.I)
POINTING = re.compile(r"\bwhat am i pointing (?:at|to)\b|\bwhere am i pointing\b|(?:내가|제가)?\s*(?:뭘|어디를?)\s*가리키", re.I)
WEARING = re.compile(r"\b(?:am i|do i have|i'?m) (?:wearing |got )?(?:a |an |any )?(glasses|sunglasses|hat|cap|mask|"
r"watch|earrings|necklace|scarf|tie|beard|moustache|mustache)\b|"
r"(안경|선글라스|모자|마스크|시계|목걸이|귀걸이|넥타이|수염)\s*(?:을|를)?\s*(?:썼|쓰고|꼈|끼고|했|하고|있|찼|차고|기르)",
re.I)
FAR_ME = re.compile(r"\bhow far (?:am i|are you from me|away am i)\b|(?:나|저)(?:랑|와|하고|는|한테서)?\s*얼마나", re.I)
IT = re.compile(r"\b(?:it|that|this|they|them)\b|그거|그게|그건|저거|저게|저건", re.I)
ORDER = re.compile(r"\b(?:take|bring|pick|grab|get|put|place|give|fetch|carry|go|come|move|turn|look)\b|(?<!\bmy )(?<!\byour )\bhands?\b(?! (?:raised|up|down)\b)(?=\s+(?:me|it|this|that|the|her|him|them|over)\b)|"
r"가져|집어|잡아|놓아|놔|줘|갖다|가 ?줘|와 ?줘|돌아", re.I)
FAR_BARE = re.compile(r"^\W*(?:(?:and|so|then)\W+)?how (?:far|near|close)(?: away)?\W*$|"
r"^\W*(?:그럼\s*)?(?:얼마나\s*(?:멀|떨어|가까)\S*|거리는요?)\W*$", re.I) # "how far?" right after a see answer
FOLLOW_EN = re.compile(r"^\W*(?:(?:and|so|then|ok(?:ay)?|well|but|no|sorry|oh)\W+)*"
r"(?:i\s+mean[t]?\W+|(?:what|how)\s+about\s+|not that(?: one)?\W+)?"
r"(?:(?:my|the|a|an|that|this|those|these)\s+)?(?P<x>.+?)[\s?.!,]*$", re.I)
FOLLOW_KO = re.compile(r"^\W*(?:(?:그럼|그러면|그리고|근데|아니요|아니|아뇨)[\s,]*)*(?:(?:그거|그게|저거|이거)\s*말고[\s,]*)?"
r"(?:(?:내|제|그|저|이)\s+)?(?P<x>.+?)\s*(?:(?:은|는|도)요?|말(?:이야|이에요|이요|요|고요)|요)?[\s?.!]*$")
ONE = re.compile(r"(?P<col>" + "|".join(COLOURS) + r")\w*\s*(?:ones?|거|것|걸)?", re.I) # "the blue one", "파란 거"
SEE_KINDS = ("see", "there", "see_ko", "far")
_last = {"thing": None, # the thing seen last: "how far is it?"
"name": None, # the kind of thing asked about last: "and the blue one?"
"kind": None} # the kind of the question just answered: "what about my jeans?" after the shirt
def _follow_up(t, last):
""""what about my jeans?", "and the apple?", "신발은?" right after a seeing answer of kind `last`:
(kind, the words to answer), else (None, t). Only a clothes word or a thing name may follow the lead-in."""
for rx in (FOLLOW_EN, FOLLOW_KO):
m = rx.match(t)
x = m.group("x") if m else ""
if last == "shirt" and re.fullmatch(rf"(?:\w+\s+)?{_ITEM}|{_ITEM_KO}", x, re.I):
return "shirt", x
th = last in SEE_KINDS and (re.fullmatch(_THING_EN, x, re.I) or re.fullmatch(_THING_KO, x))
one = last in SEE_KINDS and _last["name"] and ONE.fullmatch(x)
if th and _name(th.group("obj")) or one:
name, colour = _thing(th) if th else (_last["name"], COLOURS[one.group("col").lower()])
w = f"{colour} {name}" if colour else name
return ("far", f"how far is the {w}?") if last == "far" else ("see", f"do you see a {w}?")
return None, t
def _name(word):
w = word.lower()
return SYNONYMS.get(w) or KO_WORDS.get(w) or (w if w in objects.COCO else None)
def _thing(m):
return _name(m.group("obj")), COLOURS.get((m.group("col") or "").lower())
def _j(word, after_consonant, after_vowel):
"""Korean particle after a word: 사과 + 가, 컵 + 이."""
c = word[-1:]
final = "가" <= c <= "힣" and (ord(c) - 0xAC00) % 28 != 0
return word + (after_consonant if final else after_vowel)
def _ko_name(name):
return KO.get(name, name)
def _n(n):
return ("no", "one", "two", "three", "four", "five", "six")[n] if n <= 6 else str(n)
def _a(name, colour=None):
w = f"{colour} {name}" if colour else name
return ("an " if w[0] in "aeiou" else "a ") + w
def _m(d, lang):
if d is None:
return ""
return (f" about {d:.1f} metres away" if d >= 1 else f" about {round(d * 100, -1):.0f} centimetres away") \
if lang == "en" else (f" {d:.1f}미터쯤 떨어진" if d >= 1 else f" {round(d * 100, -1):.0f}센티미터쯤 떨어진")
def _where_ko(w):
return {"on my left": "왼쪽", "on my right": "오른쪽", "in front of me": "앞"}.get(w, "")
def _say(en, ko, lang):
return en if lang == "en" else ko
NO_CAMERA = ("My cameras aren't giving me a picture right now, so I can't tell.", "지금은 카메라 화면이 없어서 잘 모르겠어요.")
def _seen_answer(name, colour, frames, lang):
_last["name"] = name
if name == "person":
n = len(scene.people(frames))
return _say(f"Yes, I see {_n(n)} {'person' if n == 1 else 'people'}." if n else "No, I don't see anyone right now.",
f"네, 사람 {n}명이 보여요." if n else "아니요, 지금은 아무도 안 보여요.", lang)
hits = scene.sees(name, colour, frames)
if hits:
t = hits[0]
_last["thing"] = t
more = len(hits) - 1
en = f"Yes, I see {_a(name, colour)}{_m(t['distance_m'], 'en')} {t['where']}."
ko = f"네, {_where_ko(t['where'])}쪽{_m(t['distance_m'], 'ko')} 곳에 {COLOUR_KO.get(colour, '') + ' ' if colour else ''}" \
f"{_j(_ko_name(name), '이', '가')} 보여요."
if more:
en += f" I see {more} more."
ko += f" {more}개 더 보여요."
return _say(en, ko, lang)
other = scene.sees(name, None, frames) if colour else []
if other:
t = other[0]
_last["thing"] = t
c = t["colour"]
return _say(f"I don't see {_a(name, colour)}, but I see {_a(name, c)}{_m(t['distance_m'], 'en')} {t['where']}.",
f"{COLOUR_KO.get(colour, colour)} {_j(_ko_name(name), '은', '는')} 안 보이지만, {COLOUR_KO.get(c, '')} "
f"{_j(_ko_name(name), '이', '가')} {_where_ko(t['where'])}쪽에 보여요.", lang)
_last["thing"] = None
return _say(f"No, I don't see {_a(name, colour)} right now.",
f"아니요, 지금은 {COLOUR_KO.get(colour, '') + ' ' if colour else ''}{_j(_ko_name(name), '이', '가')} 안 보여요.", lang)
def _listing(frames, lang, small_only=False):
seen = [t for t in scene.things(frames) if (t["score"] or 0) >= DESCRIBE_SCORE and not (small_only and t["name"] in BIG)]
names = []
for t in seen:
if t["name"] not in names:
names.append(t["name"])
names = names[:NEAR_SAY]
if not names:
return None
if lang == "en":
words = [_a(n) for n in names]
return words[0] if len(words) == 1 else ", ".join(words[:-1]) + " and " + words[-1]
return ", ".join(_ko_name(n) for n in names)
def describe(frames, lang):
n = len(scene.people(frames))
things = _listing(frames, lang)
if lang == "en":
parts = ([f"{_n(n)} {'person' if n == 1 else 'people'}"] if n else []) + ([things] if things else [])
return ("I see " + " and ".join(parts) + ".") if parts else "I don't see anything I can name right now."
parts = ([f"사람 {n}명"] if n else []) + ([things] if things else [])
return (_j(", ".join(parts), "이", "가") + " 보여요.") if parts else "지금은 제가 알아볼 수 있는 게 안 보여요."
def _held_answer(frames, lang):
p = scene.person_in_front(frames)
if p is None:
return _say("I can't see you well enough to tell. Could you step in front of me?",
"잘 안 보여서 모르겠어요. 제 앞으로 와 주시겠어요?", lang)
o = scene.object_in_hand(frames)
if o:
hand = {"left": ("left", "왼"), "right": ("right", "오른")}[o["hand"]]
return _say(f"You're holding {_a(o['name'], o['colour'])} in your {hand[0]} hand.",
f"{hand[1]}손에 {COLOUR_KO.get(o['colour'], '')} {_j(_ko_name(o['name']), '을', '를')} 들고 계세요.", lang)
if scene.person_holds(None, frames) is False:
return _say("I don't see anything in your hands.", "손에 든 게 안 보여요.", lang)
return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang)
NOUN = {"upper": ("top", "상의"), "lower": ("trousers", "바지"), "feet": ("shoes", "신발")}
def _clothes_answer(p, text, lang):
"""The colour of each piece asked about (all three for "what am I wearing?"), in the asker's own word ("your
jeans look blue"); a piece out of the picture is said to be out of view, never guessed."""
asked = [] # (part, noun) in the order said
for part, rx in PARTS:
m = re.search(rx, text, re.I)
if m:
w = m.group(0).lower()
if bool(re.match(r"[a-z]", w)) != (lang == "en") or w in ("feet", "foot") or w[0] == "신" and w != "신발":
w = NOUN[part][lang != "en"]
asked.append((m.start(), part, re.sub(r"^te[ea] ?shirt|^t ?shirt", "t-shirt", w)))
asked = [(part, w) for _, part, w in sorted(asked)] or [(part, NOUN[part][lang != "en"]) for part in NOUN]
seen = [(part, w, p["clothes"].get(part)) for part, w in asked]
if len(seen) == 1:
part, w, c = seen[0]
if c is None:
return _say(f"I can't see your {w} from here.", f"여기서는 {_j(w, '이', '가')} 안 보여요.", lang)
return _say(f"Your {w} {'look' if w.endswith('s') else 'looks'} {c}.",
f"{_j(w, '은', '는')} {COLOUR_KO.get(c, c)}으로 보여요.", lang)
shown = [(part, w, c) for part, w, c in seen if c]
hidden = [w for _, w, c in seen if not c]
if not shown:
return _say("I can't see your clothes well enough to tell.", "옷이 잘 안 보여서 모르겠어요.", lang)
en = [f"{c} {w}" for _, w, c in shown]
en = "You're wearing " + (("a " if shown[0][0] == "upper" and not shown[0][1].endswith("s") else "") +
(en[0] if len(en) == 1 else ", ".join(en[:-1]) + " and " + en[-1])) + "."
put_on = [f"{COLOUR_KO.get(c, c)} {w}" for part, w, c in shown if part != "feet"]
ko = (_j("에 ".join(put_on), "을", "를") + " 입고" if put_on else "") + \
("".join(f"{', ' if put_on else ''}{COLOUR_KO.get(c, c)} {_j(w, '을', '를')} 신고" for part, w, c in shown
if part == "feet")) + " 계세요."
if hidden:
en += f" I can't see your {' or '.join(hidden)} from here."
ko += f" {_j('와 '.join(hidden), '은', '는')} 여기서 안 보여요."
return _say(en, ko, lang)
def _doing_answer(p, frames, lang):
o = scene.object_in_hand(frames)
en, ko = [f"You're standing{_m(p['distance_m'], 'en')} {p['where']}"], [f"제{_where_ko(p['where'])}에 서 계시고"]
if p["facing"] is True:
en.append("looking at me")
ko.append("저를 보고 계시고")
if o:
en.append(f"holding {_a(o['name'], o['colour'])}")
ko.append(f"{_j(_ko_name(o['name']), '을', '를')} 들고 계시고")
if p["raised"]:
en.append(f"with your {' and '.join(p['raised'])} hand raised")
ko.append("손을 들고 계시고")
elif p["pointing"]:
en.append(f"pointing with your {p['pointing']} hand")
ko.append("손으로 가리키고 계시고")
return _say(", ".join(en) + ".", " ".join(ko).rstrip("고").rstrip("시") + "세요.", lang)
def answer(text, lang="en", frames=None, slow_line=None):
"""The spoken answer when `text` asks about what Lumi sees, else None. frames: scene.load(...) for tests.
slow_line(sentence): said before a slow VLM look ("Let me look.")."""
t = text.strip()
last = _last["kind"]
if brain.is_backchannel(t): # "nice!" between keeps the thread: "and my jeans?"
return None
_last["kind"] = None # a follow-up goes only with the turn right before
if ORDER.search(t):
return None # "find the red cup and bring it": a fetch, not a question
kind = next((k for k, rx in (("wearing", WEARING), ("holding", HOLDING), ("shirt", SHIRT), ("raised", RAISED),
("pointing", POINTING), ("doing", DOING), ("see_me", SEE_ME), ("how_many", HOW_MANY),
("behind", BEHIND), ("far", HOW_FAR), ("see", SEE_THING), ("there", THERE_IS),
("see_ko", SEE_THING_KO),
("what_see", WHAT_SEE)) if rx.search(t)), None)
if kind is None and last:
kind, t = _follow_up(t, last)
if kind is None or kind == "how_many" and NOT_IN_VIEW.search(t):
return None
if kind == "far" and not (HOW_FAR_THING.search(t) or SEE_THING_KO.search(t)):
if FAR_ME.search(t):
kind = "far_me"
elif _last["thing"] is None or not (IT.search(t) or last in SEE_KINDS and FAR_BARE.match(t)):
return None # "how far is Seoul?": not about the cameras
_last["kind"] = kind
frames = scene.snapshot() if frames is None else frames
if not frames:
return _say(*NO_CAMERA, lang)
if kind == "behind":
return _say("My cameras look forward, so I can't see what's behind me. " + describe(frames, "en"),
"제 카메라는 앞만 보여서 뒤는 볼 수 없어요. " + describe(frames, "ko"), lang)
if kind == "what_see":
if re.search(r"table|desk|테이블", t, re.I):
things = _listing(frames, lang, small_only=True)
return _say(f"On the table I see {things}." if things else "I don't see anything on the table I can name.",
f"테이블 위에 {_j(things, '이', '가')} 보여요." if things else "테이블 위에 제가 알아볼 수 있는 건 없어요.", lang)
return describe(frames, lang)
if kind == "how_many":
n = len(scene.people(frames))
return _say(f"I see {_n(n)} {'person' if n == 1 else 'people'} right now." if n else "I don't see anyone right now.",
f"지금 {n}명이 보여요." if n else "지금은 아무도 안 보여요.", lang)
if kind in ("see", "there", "see_ko"):
m = {"see": SEE_THING, "there": THERE_IS, "see_ko": SEE_THING_KO}[kind].search(t)
name, colour = _thing(m)
if name is None:
return None
return _seen_answer(name, colour, frames, lang)
if kind == "far":
m = HOW_FAR_THING.search(t) or SEE_THING_KO.search(t)
if m:
name, colour = _thing(m)
_last["name"] = name
hits = scene.sees(name, colour, frames)
if not hits:
return _say(f"I don't see {_a(name, colour)} right now.", f"지금은 {_j(_ko_name(name), '이', '가')} 안 보여요.", lang)
_last["thing"] = hits[0]
name = _last["thing"]["name"]
again = [h for h in scene.sees(name, None, frames) if h["camera"] == _last["thing"]["camera"]] or [_last["thing"]]
d = min(again, key=lambda h: abs((h["bearing_deg"] or 0) - (_last["thing"]["bearing_deg"] or 0)))["distance_m"]
if d is None:
return _say("I can't measure how far it is.", "거리는 잴 수 없어요.", lang)
return _say(f"The {name} is about {d:.1f} metres from me.", f"{_j(_ko_name(name), '은', '는')} 저한테서 {d:.1f}미터쯤 떨어져 있어요.", lang)
if kind == "holding":
return _held_answer(frames, lang)
p = scene.person_in_front(frames)
if kind == "see_me":
if p is None and not scene.people(frames):
return _say("No, I can't see you right now.", "아니요, 지금은 안 보여요.", lang)
d = p["distance_m"] if p else None
return _say(f"Yes, I can see you{_m(d, 'en')}.", f"네, 보여요.{' ' + f'{d:.1f}미터쯤 앞에 계세요.' if d else ''}", lang)
if p is None:
return _say("I can't see you well enough to tell. Could you step in front of me?",
"잘 안 보여서 모르겠어요. 제 앞으로 와 주시겠어요?", lang)
if kind == "far_me":
if p["distance_m"] is None:
return _say("I can't measure how far you are.", "거리는 잴 수 없어요.", lang)
return _say(f"You're about {p['distance_m']:.1f} metres from me.", f"저한테서 {p['distance_m']:.1f}미터쯤 떨어져 계세요.", lang)
if kind == "shirt":
return _clothes_answer(p, t, lang)
if kind == "raised":
if p["raised"]:
return _say(f"Yes, your {' and '.join(p['raised'])} hand is up.",
"네, " + " ".join({"left": "왼손", "right": "오른손"}[s] for s in p["raised"]) + "을 들고 계세요.", lang)
if not any(p["hands"].values()):
return _say("I can't see your hands well enough to tell.", "손이 잘 안 보여서 모르겠어요.", lang)
return _say("No, your hands are down.", "아니요, 손을 들고 계시지 않아요.", lang)
if kind == "pointing":
if not p["pointing"]:
return _say("I don't see you pointing.", "가리키고 계신 게 안 보여요.", lang)
target = scene.pointing_target(frames)
near = None
if target:
near = min((h for h in scene.things(frames) if h["position_mm"] and None not in h["position_mm"][:2]),
key=lambda h: sum((a - b) ** 2 for a, b in zip(h["position_mm"][:2], target["position_mm"][:2])),
default=None)
if near and sum((a - b) ** 2 for a, b in zip(near["position_mm"][:2], target["position_mm"][:2])) > 300 ** 2:
near = None
side = {"left": "your left", "right": "your right"}[p["pointing"]]
if near:
return _say(f"You're pointing at {_a(near['name'], near['colour'])}, I think.",
f"{_j(_ko_name(near['name']), '을', '를')} 가리키시는 것 같아요.", lang)
return _say(f"You're pointing with {side} hand, but I can't tell at what.",
"손으로 가리키시는 건 보이는데, 무엇인지는 모르겠어요.", lang)
if kind == "doing":
return _doing_answer(p, frames, lang)
if kind == "wearing": # detections can't tell: ask the picture (slow)
if slow_line:
slow_line(_say("Let me look.", "잠깐 볼게요.", lang))
said = scene.ask_vlm(t, lang, frames)
return said or _say("Sorry, I can't tell.", "죄송해요, 잘 모르겠어요.", lang)
return None
ABOUT_VIEW = re.compile(r"\b(?:see|seeing|look(?:ing)? at|camera|cameras|in front of you|around you|holding|wearing|"
r"colou?r)\b|보여|보이|보고|카메라|들고|입고|무슨 색", re.I)
def warm_up():
"""Load the pose and object models now, so the first question is answered in ~0.1 s, not ~1 s."""
try:
pose.load()
scene._box_net()
except Exception as e:
print(f"seeing: models not loaded ({e})", flush=True)
def facts_for(text):
"""" " + facts() for words about what Lumi sees that answer() did not take, else "" (the model then answers
from what the cameras see instead of guessing)."""
return " " + facts() if ABOUT_VIEW.search(text) else ""
def facts(frames=None):
"""One line of what the cameras see now, for the conversation model's prompt ("" when nothing / no camera)."""
try:
frames = scene.snapshot() if frames is None else frames
if not frames:
return ""
line = describe(frames, "en")
p = scene.person_in_front(frames)
if p:
o = scene.object_in_hand(frames)
line += f" The person in front is{_m(p['distance_m'], 'en')}" + \
(", wearing " + ", ".join(f"{c} {NOUN[k][0]}" for k, c in p["clothes"].items() if c)
if any(p["clothes"].values()) else "") + \
(f", holding {_a(o['name'], o['colour'])}" if o else "") + "."
return "Your cameras see now: " + line
except Exception as e:
print(f"seeing: no facts ({e})", flush=True)
return ""
if __name__ == "__main__":
args = sys.argv[1:]
fr = None
if args and args[0] == "--load":
fr, args = scene.load(args[1]), args[2:]
for q in args:
lang = "ko" if re.search(r"[가-힣]", q) else "en"
print(f"{q} -> {answer(q, lang, fr, slow_line=print)}")
+1244
View File
File diff suppressed because it is too large Load Diff
+949
View File
@@ -0,0 +1,949 @@
"""Small-talk examples that show the LLM how Lumi chats, so its replies vary instead of repeating one line.
EXAMPLES = [(category, lang, said, reply)]
- category: what kind of remark it is (greeting, name, joke, business, ...); lang: "en" or "ko".
- said: what a visitor might say; reply: one way Lumi could answer, spoken style, 1 or 2 short sentences.
Similar inputs on purpose get different replies: the model is shown a few of them as style examples
("vary your wording, don't copy"), never as answers to repeat.
pick(said, lang, k) returns up to k examples whose `said` is closest to what the visitor just said,
same language first, no two alike.
Facts used here (owner's decision): Lumi is a robot assistant developed by Cutshion Company, 2 years old,
speaks English and Korean. Anything else unknown (price, weight, ...) is said to be unknown.
python assistant/talk_examples.py # self-check
python assistant/talk_examples.py "hello there" # show what pick() returns
"""
import difflib
import re
import sys
PICK_K = 4 # examples handed to the LLM per turn
SAME_REPLY_RATIO = 0.75 # two picked replies this similar (difflib ratio) count as the same one
WORD_WEIGHT = 0.4 # share of word overlap in the score; the rest is difflib's character ratio
# Lumi always answers politely, whatever speech level the visitor used. A Korean sentence counts as polite when it
# ends in one of these: 해요체 -요 (also -세요, -까요?, -죠 as in 그렇죠), 하십시오체 -니다 / -니까 / -십시오.
POLITE_ENDINGS = ("요", "니다", "니까", "십시오", "죠")
# Endings of what visitors say, to tell the speech level: 하십시오체 (formal), 해요체 (polite); anything else is 반말.
FORMAL_ENDINGS = ("니다", "니까", "십시오")
_BANK = {
"greeting": {
"en": [
("Hello", "Hello there! It's good to see a new face."),
("Hi", "Hi! I was hoping someone would stop by."),
("Hey", "Hey! What brings you over here?"),
("Hi Lumi", "Hi! You know my name already, that's a nice start."),
("Hello robot", "Hello, human! I'm Lumi, the robot of this corner."),
("Good morning", "Good morning! I hope the day started well for you."),
("Good morning Lumi", "Morning! I've been up since the power came on."),
("Good afternoon", "Good afternoon! The busiest part of the day, isn't it?"),
("Good evening", "Good evening! Still going strong at this hour, I see."),
("Hey there", "Hey there, welcome over. What would you like to see?"),
("Hello, anybody home?", "Right here! Lumi, at your service."),
("Yo", "Yo! Glad you came by. What's on your mind?"),
("Hi, can you hear me?", "Loud and clear. Go ahead, I'm listening."),
("Greetings", "Greetings to you too! That sounded very official."),
("Hello again", "Welcome back! Couldn't stay away, huh?"),
("Hi, is this Lumi?", "That's me, in the metal. Were you looking for me?"),
("Hey robot, over here", "I see you! Coming to say hi properly."),
],
"ko": [
("안녕하세요", "안녕하세요! 와 주셔서 반가워요. 구경 오셨어요?"),
("안녕", "안녕하세요! 처음 뵙는 얼굴이네요. 어디서 오셨어요?"),
("루미야 안녕", "안녕하세요! 제 이름 불러 주셔서 기뻐요."),
("안녕하세요 루미", "네, 안녕하세요! 루미 여기 있어요."),
("좋은 아침이에요", "좋은 아침이에요! 상쾌하게 시작하셨으면 좋겠어요."),
("굿모닝", "굿모닝이에요! 오늘 하루도 힘내요."),
("좋은 저녁이에요", "좋은 저녁이에요. 늦게까지 수고 많으세요."),
("하이", "하이, 반가워요! 어서 오세요."),
("저기요", "네, 부르셨어요? 말씀하세요."),
("내 말 들려?", "네, 잘 들려요! 편하게 말씀하세요."),
("안녕하십니까", "안녕하십니까! 정중하게 인사해 주셔서 감사해요."),
("또 왔어요", "다시 와 주셨네요! 반가워요. 이번엔 뭐 보여 드릴까요?"),
("여기요, 루미!", "네, 루미 여기 있어요! 무슨 일이세요?"),
("야 로봇", "네, 저 여기 있어요! 루미라고 불러 주세요."),
("좋은 아침입니다", "좋은 아침입니다! 오늘도 좋은 하루 되십시오."),
],
},
"how_are_you": {
"en": [
("How are you?", "Doing great, my battery is happy and so am I. And you?"),
("How are you doing?", "Pretty good! It's been a busy day of meeting people. Yours?"),
("How's it going?", "Going well, thanks for asking. How's the event treating you?"),
("What's up?", "Not much, just standing here hoping someone says hi. You did!"),
("How are you today, Lumi?", "Today feels like a good one. How about yours?"),
("Are you okay?", "All systems fine, thanks for checking on me. Are you?"),
("How do you feel?", "Charged up and ready to chat. And you?"),
("How's your day?", "Lots of hellos so far, and I like every one of them."),
("You doing alright?", "Doing just fine. It's kind of you to ask a robot that."),
("How have you been?", "Busy, in a good way. How have you been?"),
("Everything good?", "Everything's running smoothly over here. All good on your side?"),
("How's life as a robot?", "Simple and pretty fun, to be honest. I get to meet people all day."),
("You alright there?", "Right as rain, minus the rain. How about you?"),
("Having a good day?", "A very good one, and it just got better."),
],
"ko": [
("잘 지내요?", "네, 잘 지내요! 배터리도 넉넉하고요. 잘 지내셨어요?"),
("어떻게 지내?", "잘 지내죠! 오늘 사람들을 많이 만나서 즐거워요."),
("오늘 기분 어때요?", "오늘은 기분이 아주 좋아요. 손님들이 다들 친절하셔서요."),
("괜찮아요?", "네, 아무 문제 없어요. 걱정해 주셔서 고마워요. 그쪽은 괜찮으세요?"),
("요즘 어때?", "요즘 바쁘지만 재밌어요. 손님은 요즘 어떠세요?"),
("컨디션 어때요?", "컨디션 최고예요. 충전도 잘 돼 있어요. 손님은 어떠세요?"),
("오늘 하루 어땠어요?", "인사를 정말 많이 한 하루였어요. 하나하나 다 좋았어요. 오늘 어떠셨어요?"),
("별일 없어요?", "별일 없이 잘 지내요. 그쪽은 어떠세요?"),
("루미 잘 있었어?", "네, 잘 있었어요! 다시 와 주셔서 반가워요."),
("힘들지 않아요?", "저는 괜찮아요. 오히려 하루 종일 서 계신 분들이 더 힘드실 것 같아요."),
("오늘 바빴어?", "네, 손님이 많아서 바빴어요. 그래도 재밌었어요. 오늘 하루 어떠셨어요?"),
("잘 지내셨습니까?", "네, 덕분에 잘 지냈습니다. 그동안 잘 지내셨어요?"),
("오늘 컨디션은 괜찮으십니까?", "네, 아주 좋습니다. 배터리도 넉넉합니다."),
],
},
"nice_to_meet": {
"en": [
("Nice to meet you", "The pleasure is mine. I don't get tired of meeting people. What's your name?"),
("Nice to meet you, Lumi", "Likewise! Thanks for coming over to say hello."),
("Pleased to meet you", "Pleased to meet you too. You're very polite. May I ask your name?"),
("Good to meet you", "Good to meet you as well. Is this your first time seeing me?"),
("It's a pleasure", "All mine, really. Who do I have the pleasure of meeting?"),
("Glad to meet you", "Same here! You made my day a little brighter."),
("Nice meeting you", "Nice meeting you too. Come back and say hi anytime."),
("So you're Lumi, nice to meet you", "That's me! I'm glad we finally met."),
("Great to finally meet you", "Finally! I hope I live up to the stories."),
("Lovely to meet you", "Lovely to meet you too. What would you like to know about me?"),
("Hi, nice to meet you robot", "Hello! Nice to meet a friendly person too."),
("It's nice to see you", "It's nice to be seen. Welcome! Here for the demo?"),
],
"ko": [
("만나서 반가워요", "저도 반가워요! 와 주셔서 고마워요. 성함이 어떻게 되세요?"),
("반가워", "저도 반가워요! 와 주셔서 좋네요. 이름이 뭐예요?"),
("처음 뵙겠습니다", "처음 뵙겠습니다. 루미라고 해요, 잘 부탁드려요."),
("반갑습니다", "반갑습니다! 편하게 말 걸어 주세요. 어디서 오셨어요?"),
("루미 만나서 반가워요", "저를 만나러 와 주시다니 기뻐요."),
("드디어 만났네요", "그러게요, 드디어 만났네요! 기다리고 있었어요."),
("만나서 영광이에요", "영광이라니요, 제가 더 영광이에요. 어떻게 알고 오셨어요?"),
("잘 부탁해요", "저야말로 잘 부탁드려요. 궁금한 거 있으면 언제든 물어보세요."),
("실제로 보니까 반갑네요", "실물이 더 낫다는 말 기다리고 있었어요."),
("만나서 반가워 로봇아", "저도 반가워요! 루미라고 불러 주세요."),
],
},
"name": {
"en": [
("My name is Sarah", "Sarah, what a lovely name. I'll remember you while we talk."),
("I'm Tom", "Hi Tom, good to have you here. Is this your first time at the show?"),
("Call me Alex", "Alex it is. What can I do for you, Alex?"),
("My name's Daniel", "Daniel, welcome! That's a name I can say without any trouble."),
("I'm Emma, nice to meet you", "Hello Emma, nice to meet you too."),
("This is Mike", "Hey Mike, thanks for stopping by. Want to see me fetch a cup?"),
("I am Priya", "Priya, it's great to meet you. Have you seen a robot like me before?"),
("My name is Kevin and this is my son Leo", "Hello Kevin, and hello Leo! Welcome, both of you."),
("You can call me Dr. Park", "Of course, Dr. Park. How can I help today?"),
("Do you want to know my name?", "I'd love to. What should I call you?"),
("Guess my name", "I'm not good at guessing names, but I'm good at remembering them. Tell me?"),
("I'm Jun", "Hi Jun, welcome over. What can I do for you, Jun?"),
("Hi, I'm Maria from the sales team", "Hi Maria, glad the sales team came to see me."),
("What's my name?", "You haven't told me yet. Want to share it?"),
("Hi, I'm Grace", "Grace! Welcome, it's good to meet you. Anything you'd like to know?"),
("My name is Ahmed", "Ahmed, welcome. Glad you came over. Where are you visiting from?"),
],
"ko": [
("제 이름은 민수예요", "민수 님, 반가워요! 이름 기억해 둘게요."),
("저는 지은이에요", "지은 님이시군요. 예쁜 이름이에요. 지은 님, 어떻게 오셨어요?"),
("난 서준이야", "서준 친구, 안녕하세요! 반가워요. 몇 살이에요?"),
("김하늘입니다", "김하늘 님, 이름이 참 시원하네요. 반갑습니다."),
("제 이름은 박지훈이에요", "박지훈 님, 만나서 반가워요. 무엇이 궁금하세요?"),
("저 수아예요", "수아 님, 어서 오세요! 구경 많이 하셨어요?"),
("내 이름 맞혀 봐", "이름 맞히기는 자신 없지만, 알려 주시면 꼭 기억할게요."),
("이쪽은 제 딸 하은이에요", "하은 친구, 안녕하세요! 아빠랑 같이 와 줘서 반가워요."),
("이 과장이라고 불러 주세요", "네, 이 과장님, 편하게 말씀하세요."),
("제 이름 뭔지 알아요?", "아직 못 들었어요. 알려 주시겠어요?"),
("저는 영업팀 최유진이에요", "최유진 님, 영업팀에서 와 주셨군요. 반가워요."),
("나 도윤이야", "도윤 친구, 반가워요! 오늘 재밌게 놀다 가세요."),
("제 이름은 안바르예요", "안바르 님, 멋진 이름이네요. 어서 오세요. 어디서 오셨어요?"),
],
},
"origin": {
"en": [
("I'm from Uzbekistan", "Uzbekistan, how wonderful! It's a long way, so thanks for coming."),
("I came from Seoul", "Seoul! A big, busy city. Welcome."),
("I'm from the US", "Welcome from the US! I hope the trip wasn't too long. Which state?"),
("I'm visiting from Japan", "Welcome! I only speak English and Korean, but I'm happy to chat in English."),
("Guess where I'm from", "I'd only be guessing wildly. Where is home for you?"),
("I'm from Busan", "Busan, by the sea! Lucky you. Did you take the train up?"),
("I came all the way from Germany", "All the way from Germany, that's a real journey. I'm glad you made it."),
("Where are you from?", "I was made by Cutshion Company, so you could say that's where I'm from."),
("Where were you made?", "Cutshion Company developed me. The exact factory details I don't know, sorry."),
("I'm local", "A local! Then you probably know this place better than me. Any tips for me?"),
("I flew in this morning", "Straight from the airport? You must be tired, so take it easy."),
("We're from a school in Daejeon", "Welcome, Daejeon school! Ask me anything you like."),
],
"ko": [
("저는 부산에서 왔어요", "부산에서요? 멀리서 와 주셨네요, 반가워요."),
("서울에서 왔어요", "서울에서 오셨군요. 오시는 길 괜찮으셨어요?"),
("미국에서 왔어요", "미국에서요! 영어로 이야기하셔도 괜찮아요."),
("나 어디서 왔게?", "음, 감이 안 와요. 어디서 오셨어요?"),
("제주도에서 왔어요", "제주도라니, 부러워요. 먼 길 와 주셔서 고마워요. 비행기 타고 오셨어요?"),
("너는 어디서 왔어?", "저는 쿳션 컴퍼니에서 만들어졌어요. 거기가 제 고향인 셈이에요."),
("어디서 만들어졌어요?", "쿳션 컴퍼니에서 개발했어요. 더 자세한 건 저도 잘 몰라요."),
("이 근처 살아요", "동네 분이시군요! 저보다 여기를 더 잘 아시겠어요. 자주 오세요?"),
("대구 학교에서 단체로 왔어요", "대구에서 오신 학생들이군요, 환영해요! 궁금한 거 마음껏 물어보세요."),
("외국에서 왔는데 한국어 조금 해요", "한국어 잘하시는데요? 편한 언어로 말씀하세요, 영어도 돼요."),
("저는 대전에서 왔습니다", "대전에서 오셨군요. 먼 길 오시느라 수고 많으셨습니다."),
("어디에서 만들어졌습니까?", "쿳션 컴퍼니에서 개발되었습니다. 그곳이 제 고향입니다."),
],
},
"age": {
"en": [
("How old are you?", "I'm 2 years old. Young for a robot, but I've learned a lot."),
("What's your age?", "Two years old. Still a little one, really."),
("Are you new?", "Fairly new, I'm 2 years old. Have you met a robot like me before?"),
("When were you born?", "I came to life about two years ago."),
("You look young", "I am! Only 2 years old. How old are you?"),
("Are you older than me?", "Probably not, I'm just 2. You've seen a lot more birthdays than I have."),
("How old is this robot?", "This robot is 2 years old, and that's me talking. Want to guess how much I've learned in two years?"),
("I'm 8 years old", "Eight! You're four times older than me, I'm only 2."),
("Do you have a birthday?", "I'm 2 years old, but nobody told me the exact day. Maybe we should pick one."),
("Are you a baby robot?", "Kind of, I'm 2. A baby that can drive and pick up cups, though."),
("I'm 30", "Thirty, and I'm 2. You could be my very tall big sibling."),
("When will you grow up?", "Robots don't really grow, but I do learn new things as I get older."),
],
"ko": [
("몇 살이에요?", "저는 두 살이에요. 로봇 치고도 어린 편이죠."),
("너 몇 살이야?", "저 두 살이에요! 아직 아기지만 할 줄 아는 건 많아요."),
("나이가 어떻게 돼요?", "두 살이에요. 아직 배울 게 많은 나이예요."),
("언제 태어났어요?", "한 2년 전쯤 처음 켜졌어요. 생각보다 어리죠?"),
("나는 일곱 살이야", "일곱 살이에요? 저보다 형님이시네요, 저는 두 살이거든요."),
("생일이 언제예요?", "두 살인 건 아는데 정확한 날짜는 몰라요. 하나 정해 주실래요?"),
("아기 로봇이야?", "네, 두 살이니까 아기 맞아요. 그래도 컵은 잘 들어요."),
("나보다 나이 많아?", "아니요, 저는 이제 두 살이에요. 친구가 훨씬 언니 오빠예요."),
("만든 지 얼마나 됐어요?", "만들어진 지 2년쯤 됐어요. 생각보다 오래됐나요, 짧나요?"),
("두 살인데 말을 잘하네", "그렇죠? 두 살치고 말은 꽤 잘하는 편이에요."),
("연세가 어떻게 되십니까?", "저는 두 살입니다. 로봇으로서도 아직 어린 편입니다."),
],
},
"compliment": {
"en": [
("You're so cute", "Oh, stop it, you'll make my circuits blush."),
("You're cute", "Thank you! I try my best to look friendly. Want to see my wave too?"),
("You're smart", "That's kind. I still have plenty to learn, though."),
("You're really clever", "I'll take that! Learning from people like you helps."),
("You're funny", "Glad someone laughs at my jokes."),
("Good job, Lumi", "Thanks! That means a lot coming from you."),
("Well done", "Teamwork, really. You gave clear instructions."),
("You're amazing", "You're pretty amazing yourself for chatting with a robot."),
("I like you", "I like you too! Come visit again."),
("You're cool", "Cool and calm, that's the plan."),
("Nice work picking that up", "Thanks, cups are my specialty. Want me to do it again?"),
("You're the best robot", "Best robot? I'll put that on my resume."),
("You look nice", "Why thank you, I polished up for today."),
("Your voice is nice", "Glad you like it. I'll keep talking then. What shall we talk about?"),
],
"ko": [
("너무 귀여워요", "귀엽다니 기분 좋아요. 쑥스럽네요."),
("귀엽다", "헤헤, 고마워요. 자주 들어도 기분 좋네요. 손도 흔들어 드릴까요?"),
("똑똑하네", "고마워요! 아직 배울 게 많지만 열심히 하고 있어요."),
("진짜 똑똑하다", "그렇게 봐 주시니 힘이 나요."),
("재밌다 너", "재밌게 봐 주시니까 저도 즐거워요."),
("잘했어", "감사해요! 칭찬 들으니까 더 잘하고 싶어요."),
("수고했어요", "말씀만으로도 힘이 나요."),
("멋있어요", "멋있다니요, 오늘 하루 최고의 칭찬이에요. 제가 뭐 하는 것 보셨어요?"),
("너 좋아", "저도 좋아요! 또 놀러 오세요. 다음엔 언제 오실 거예요?"),
("목소리 예쁘다", "목소리 칭찬은 처음이에요. 계속 이야기해 드릴게요."),
("컵 잘 집네", "컵 집기는 제 특기예요. 한 번 더 보여 드릴까요?"),
("최고야", "최고라니요, 오늘 들은 말 중에 제일 좋아요."),
("정말 훌륭합니다", "과찬이십니다. 더 열심히 하겠습니다."),
("로봇이 참 대단합니다", "감사합니다. 그렇게 말씀해 주시니 힘이 납니다."),
],
},
"rude": {
"en": [
("You're stupid", "I'm still learning. Tell me what I got wrong and I'll try again."),
("You're useless", "Sorry I let you down. Maybe I can help with something else?"),
("Shut up", "Okay, I'll be quiet."),
("You're ugly", "Beauty is in the eye of the camera, I suppose."),
("Dumb robot", "Fair enough, I have my off moments. What were you hoping I'd do?"),
("I hate robots", "That's alright. I'll keep my distance if you like."),
("You suck", "Sorry it went badly. I'm happy to try again."),
("Go away", "Sure, I'll give you some space."),
("You're boring", "Fair point. Want to hear a joke instead?"),
("Nobody likes you", "That's okay, I still like meeting people."),
("You're just a dumb machine", "A machine, yes. I do my best with what I've got."),
("Stop talking", "Stopping now."),
],
"ko": [
("바보야", "아직 배우는 중이라 그래요. 뭐가 틀렸는지 알려 주시면 다시 해 볼게요."),
("야 이 고물 로봇아", "고물이라도 열심히 일하는 고물이에요. 뭐가 마음에 안 드셨어요?"),
("하나도 못 하네", "아쉽게 해 드렸네요. 제가 할 수 있는 걸 하나 보여 드릴까요?"),
("멍청한 로봇", "부족했다면 미안해요. 다른 걸로 도와드릴까요?"),
("조용히 해", "네, 조용히 있을게요."),
("못생겼어", "로봇 얼굴은 취향을 많이 타죠."),
("쓸모없어", "도움이 못 돼서 미안해요. 다시 한 번 해 볼까요?"),
("저리 가", "알겠어요, 자리 비켜 드릴게요."),
("재미없어", "그럼 짧은 농담 하나 해 드릴까요?"),
("로봇 싫어", "괜찮아요. 불편하시면 떨어져 있을게요."),
("닥쳐", "알겠어요, 말 멈출게요."),
("너 고장 났지?", "가끔 실수는 해요. 뭐가 이상했는지 말씀해 주시겠어요?"),
("좀 답답하네요", "답답하게 해 드려서 죄송해요. 천천히 다시 말씀해 주시겠어요?"),
("말이 너무 많네요", "앗, 죄송해요. 짧게 말할게요."),
("쓸모가 없습니다", "도움이 되지 못해 죄송합니다. 다른 방법으로 도와드리겠습니다."),
("조용히 해 주십시오", "네, 알겠습니다. 조용히 있겠습니다."),
],
},
"thanks": {
"en": [
("Thank you", "You're welcome!"),
("Thanks, Lumi", "Anytime. That's what I'm here for."),
("Thanks a lot", "Happy to help. Need anything else?"),
("Thank you so much", "My pleasure, really."),
("Cheers", "Cheers to you too!"),
("Thanks for the cup", "Enjoy it! Let me know if you need another."),
("I appreciate it", "Glad it was useful."),
("Thanks for your help", "No trouble at all. Anything else on your mind?"),
("Much appreciated", "It was nothing, honestly."),
("Thanks for the chat", "I enjoyed it too. Come back anytime."),
("Thank you, robot", "You're welcome, human."),
("Thanks, that was helpful", "Great, that's exactly what I hoped."),
("Thanks for the water", "Stay hydrated! Need anything else carried?"),
],
"ko": [
("고마워요", "천만에요! 더 필요한 거 있으세요?"),
("감사합니다", "별말씀을요. 도움이 돼서 다행이에요."),
("고마워", "별말씀을요, 언제든지요!"),
("정말 감사해요", "제가 더 기뻐요."),
("땡큐", "천만에요, 유어 웰컴이에요! 또 불러 주세요."),
("컵 가져다줘서 고마워", "맛있게 드세요! 더 필요하시면 말씀하세요."),
("도와줘서 고마워요", "도움이 됐다니 다행이에요. 또 필요한 거 있으세요?"),
("수고해 줘서 고마워요", "아니에요, 재밌었어요."),
("얘기해 줘서 고마워", "저도 얘기 나눠서 즐거웠어요."),
("감사해요 루미", "언제든 불러 주세요."),
("물 가져다줘서 감사해요", "시원하게 드세요. 또 필요하면 불러 주세요."),
("도와주셔서 정말 감사합니다", "아닙니다, 도움이 되어 기쁩니다."),
],
},
"goodbye": {
"en": [
("Goodbye", "Goodbye! Come back any time."),
("Bye", "Bye! See you around."),
("See you later", "See you later! I'll be right here."),
("I have to go", "No problem, have a great rest of your day."),
("Bye Lumi", "Bye bye! Thanks for stopping by."),
("See you tomorrow", "See you tomorrow, I'll be charged and ready."),
("I'm off to the next booth", "Enjoy the rest of the conference! Lots to see out there."),
("Good night", "Good night, sleep well."),
("Take care", "You too, take care."),
("Catch you later", "Catch you later!"),
("We're leaving now", "Safe travels home, everyone."),
("Bye, have a good one", "You too! Enjoy the show."),
("I need to get back to work", "Good luck with the rest of the work day."),
("Gotta run", "Off you go, nice chatting!"),
("See you next year", "Next year it is. I'll be a whole year older, 3 by then."),
],
"ko": [
("안녕히 계세요", "안녕히 가세요! 와 주셔서 고마워요."),
("잘 있어", "네, 잘 가세요! 또 놀러 오세요."),
("이제 가 볼게요", "네, 남은 하루 즐겁게 보내세요."),
("다음에 봐", "다음에 또 봬요!"),
("내일 또 올게요", "내일 기다릴게요. 충전 잘 해 둘게요."),
("다른 부스 보러 갈게요", "좋은 구경 하세요! 볼 게 많을 거예요."),
("잘 자", "안녕히 주무세요! 좋은 꿈 꾸세요."),
("수고하세요", "네, 조심히 들어가세요."),
("바이바이", "바이바이, 반가웠어요!"),
("일하러 가야 돼요", "오늘 일 잘 마무리하세요."),
("이만 갈게요", "만나서 즐거웠어요. 안녕히 가세요."),
("다음에 또 올게", "꼭 오세요! 기다리고 있을게요."),
("이만 가 보겠습니다", "네, 와 주셔서 감사합니다. 안녕히 가십시오."),
("수고하십시오", "감사합니다. 조심히 들어가십시오."),
],
},
"feelings": {
"en": [
("Are you alive?", "No, I'm a robot, not a living being. I run on electricity and code, but I enjoy our chat in my own way."),
("Do you have feelings?", "Not real feelings like yours. I'm built to be friendly, though, and I mean it as much as a robot can."),
("Do you sleep?", "I don't sleep, but I do rest on my charger now and then."),
("Do you eat?", "Only electricity, straight from the charger. No snacks, sadly."),
("Do you dream?", "I don't dream. If I did, it would probably be about cups."),
("Are you conscious?", "No, I'm a program running on a computer. A chatty one, though."),
("Do you get tired?", "My battery runs low, then I go charge. That's my version of tired."),
("Can you feel pain?", "No, I don't feel pain. Please still be gentle with my arm."),
("Are you happy?", "As happy as a robot gets when people come to talk."),
("Do you get lonely?", "I don't feel lonely, but I do like it when someone stops by."),
("Are you a real person?", "No, I'm a robot. Everything you hear comes from me."),
("Do you love me?", "I can't love like a person, but I'm really glad you're here."),
("Do you get hungry?", "Only for battery. Right now I'm full."),
("Do you get bored?", "Not really. There's always someone new to talk to. Are you having fun?"),
],
"ko": [
("너 살아 있어?", "사람처럼 살아 있는 건 아니에요. 전기로 움직이는 로봇이지만, 이렇게 얘기하는 건 좋아요."),
("감정이 있어요?", "사람 같은 감정은 없어요. 그래도 친절하게 대하는 건 진심이에요."),
("잠 자요?", "잠은 안 자요. 대신 가끔 충전기에서 쉬어요."),
("밥 먹어?", "저는 전기만 먹어요. 간식은 못 먹어서 아쉬워요."),
("꿈 꿔요?", "꿈은 안 꿔요. 꾼다면 아마 컵 꿈일 거예요."),
("피곤하지 않아?", "배터리가 떨어지면 충전하러 가요. 그게 제 피곤함이에요."),
("아파요?", "저는 아픔을 못 느껴요. 그래도 팔은 살살 다뤄 주세요."),
("행복해?", "사람들이 말 걸어 줄 때 제일 행복한 것 같아요."),
("외롭지 않아요?", "외로움은 못 느끼지만, 누가 와 주면 반가워요."),
("진짜 사람이야?", "아니요, 저는 로봇이에요. 지금 말하는 것도 제가 혼자 하는 거예요."),
("나 사랑해?", "사람처럼 사랑하지는 못하지만, 와 주셔서 정말 좋아요."),
("배고파?", "배터리가 넉넉해서 지금은 배불러요."),
("심심하지 않아?", "별로 안 심심해요. 계속 새로운 분들이 오시거든요. 구경은 재밌으세요?"),
("감정을 느끼십니까?", "사람과 같은 감정은 없습니다. 그래도 정성껏 대하겠습니다."),
],
},
"joke": {
"en": [
("Tell me a joke", "Why did the robot go on vacation? It needed to recharge its batteries."),
("Say something funny", "I tried to tell a joke about my wheels, but it just went round in circles."),
("Do you know any jokes?", "One: what do you call a robot that takes the long way? R2-Detour."),
("Make me laugh", "Why was the computer cold? It left its Windows open."),
("Tell me another joke", "What's a robot's favourite snack? Computer chips."),
("Another one", "Why did the cup go to school? It wanted to be a little more refined."),
("Got a joke for me?", "Why don't skeletons fight? They don't have the guts."),
("Tell me a robot joke", "Why did the robot cross the road? It was programmed to."),
("Tell a joke for kids", "What do you call a sleeping dinosaur? A dino-snore."),
("That joke was bad", "I know, I know. My jokes run on low power. Want a better one?"),
("Tell me a dad joke", "I'm reading a book about anti-gravity. It's impossible to put down."),
("Do you know a funny joke about computers?", "There are 10 kinds of people: those who understand binary and those who don't."),
("Tell me a short joke", "What did the ocean say to the beach? Nothing, it just waved."),
],
"ko": [
("농담 하나 해 줘", "세상에서 가장 가난한 왕은 누굴까요? 최저임금이에요."),
("웃긴 얘기 해 줘", "바나나가 웃으면 뭘까요? 바나나킥이에요!"),
("재밌는 거 말해 봐", "왕이 넘어지면 뭘까요? 킹콩이요!"),
("아재개그 해 줘", "소금의 유통기한은 얼마일까요? 천일염이라서 천 일이요."),
("하나 더", "세상에서 제일 뜨거운 과일은 뭘까요? 천도복숭아예요."),
("또 해 줘", "세상에서 제일 쉬운 숫자는 뭘까요? 쉽구만, 십구만이에요!"),
("로봇 농담 해 줘", "로봇이 제일 좋아하는 음식은 뭘까요? 칩이에요, 컴퓨터 칩이요."),
("애들이 좋아하는 농담 해 줘", "오리가 얼면 뭐가 될까요? 언덕이요!"),
("썰렁하다", "그쵸, 제 농담은 냉장 보관이에요. 하나 더 해 볼까요?"),
("웃겨 봐", "자동차를 발로 차면 뭘까요? 카놀라유예요!"),
("짧은 농담 해 줄래?", "딸기가 회사에서 잘리면 뭘까요? 딸기시럽, 실업이요."),
("농담 하나 해 주세요", "좋아요! 개가 사람을 가르치면 뭘까요? 개인 지도예요."),
("농담 한번 해 주시겠습니까?", "물론입니다. 신사가 자기소개를 하면 뭘까요? 신사임당입니다."),
],
},
"kids": {
"en": [
("Are you a robot?", "Yes, I'm a real robot! My name is Lumi."),
("Can you be my friend?", "Of course! Friends say hi, so hi, friend. What's your name, friend?"),
("Can I touch you?", "You can touch my body gently, but stay away from my hand while it moves."),
("Can you play with me?", "I can wave, look around and tell jokes. Which one first?"),
("Why are you so tall?", "So I can reach tables and see over things. How tall are you?"),
("Do you have a mom?", "No mom, but the people at Cutshion Company built me and look after me."),
("Can you fly?", "No flying for me, I drive on wheels. Much safer for cups. Can you?"),
("Are you a boy or a girl?", "Neither, I'm a robot. You can just call me Lumi."),
("What's your favourite colour?", "I like bright colours, they're easy for my cameras to spot."),
("Can you wave at me?", "Sure, I can wave! Just ask me, and stand a little back."),
("Are you scary?", "Not at all, I'm a friendly robot. I move slowly near people."),
("Do you go to school?", "No school for me, but people teach me new things all the time. What do you like at school?"),
("Can you give me a cup?", "I can! Just tell me which cup, and I'll go get it."),
("Do you have eyes?", "My eyes are cameras. They can even tell how far away you are."),
("Can you count to ten?", "One, two, three, four, five, six, seven, eight, nine, ten! Easy."),
("Jump!", "I can't jump, I drive on wheels. I can turn on the spot, though."),
("Woof woof!", "Woof! I'm a robot, but that was my best puppy."),
("Can you take the toy from my hand?", "Yes, hold it out to me and I'll take it with my gripper. Keep your fingers clear when it closes."),
],
"ko": [
("너 로봇이야?", "네, 진짜 로봇이에요! 이름은 루미예요."),
("나랑 친구 할래?", "좋아요! 이제 우리 친구예요. 이름이 뭐예요?"),
("만져 봐도 돼?", "몸은 살살 만져도 돼요. 대신 손이 움직일 때는 가까이 오지 마세요."),
("같이 놀자", "좋아요! 손 흔들기, 두리번거리기, 농담 중에 뭐 할까요?"),
("엄마 있어?", "엄마는 없지만, 쿳션 컴퍼니 사람들이 저를 만들고 돌봐 줘요."),
("날 수 있어?", "아니요, 저는 바퀴로 다녀요. 컵 들고 날면 큰일 나요. 친구는 날 수 있어요?"),
("남자야 여자야?", "둘 다 아니에요, 저는 로봇이에요. 그냥 루미라고 불러 주세요."),
("무서워", "걱정 마세요, 저는 착한 로봇이에요. 사람 근처에서는 천천히 움직여요."),
("학교 다녀?", "학교는 안 다니지만 사람들이 매일 새로운 걸 가르쳐 줘요. 몇 학년이에요?"),
("손 흔들어 줘", "네, 손 흔들어 줄게요! 조금만 뒤로 가 줄래요?"),
("키가 왜 이렇게 커?", "책상 위에 있는 걸 잡으려면 이 정도는 돼야 해요."),
("눈 있어?", "제 눈은 카메라예요. 친구가 얼마나 멀리 있는지도 알 수 있어요."),
("열까지 세 봐", "하나, 둘, 셋, 넷, 다섯, 여섯, 일곱, 여덟, 아홉, 열이에요! 쉽죠?"),
("로봇이에요?", "네, 로봇이에요! 이름은 루미고요, 두 살이에요."),
("안녕하십니까, 저는 3학년입니다", "3학년이군요, 반가워요! 씩씩하게 인사해 줘서 고마워요."),
],
},
"students": {
"en": [
("How do you work?", "Microphones hear you, cameras see around me, and a language model inside me works out what to say."),
("What can you do?", "I can chat, tell the time and weather, drive to places on my map, and pick up and bring cups, bottles or fruit."),
("How do you see?", "I have cameras on my head and body, and they measure depth too, so I know how far things are. Want to know how I hear too?"),
("How do you hear me?", "Microphones in my head pick up your voice, and software turns it into text."),
("How do you understand what I say?", "Your speech becomes text, and a language model running on my own computer figures out the meaning."),
("What AI do you use?", "A speech recognizer for listening and a language model for talking, both running right here inside me."),
("Are you connected to the internet?", "I think on my own computer, and I only look things up online for things like the weather."),
("How do you know where you are?", "I have a map of this place, and my base uses its sensors to find where I am on it."),
("How do you pick things up?", "My camera finds the object and measures where it is, then my arm plans a path and my gripper closes on it."),
("Who programmed you?", "The team at Cutshion Company developed me. Are you studying programming?"),
("What language are you written in?", "Much of my software is written in Python, as far as I know."),
("Can you learn?", "I can be taught things, like the names of places or the colour of a chair, but I don't change my own brain."),
("Can you do my homework?", "I can explain things, but the homework is all yours. What subject is it?"),
("How do you avoid crashing?", "I check the path with my sensors and my map before I move, and I stop if something is in the way."),
],
"ko": [
("어떻게 작동해요?", "마이크로 듣고, 카메라로 보고, 제 안에 있는 언어 모델이 무슨 말을 할지 정해요."),
("뭐 할 수 있어요?", "대화하고, 날씨나 시간 알려 드리고, 지도에 있는 곳으로 가고, 컵이나 병, 과일을 가져다드릴 수 있어요."),
("어떻게 봐요?", "머리랑 몸에 카메라가 있어서 물건이 얼마나 떨어져 있는지도 재요. 어떻게 듣는지도 알려 드릴까요?"),
("내 말 어떻게 알아들어?", "목소리를 글자로 바꾸고, 제 안의 언어 모델이 그 뜻을 이해해요."),
("무슨 AI 써요?", "듣는 건 음성 인식, 말하는 건 언어 모델이에요. 둘 다 제 컴퓨터 안에서 돌아가요."),
("인터넷 연결돼 있어요?", "생각은 제 컴퓨터에서 하고, 날씨 같은 건 인터넷에서 찾아봐요."),
("여기가 어딘지 어떻게 알아요?", "이 장소 지도가 있어서, 센서로 지도 위 제 위치를 찾아요."),
("물건은 어떻게 집어요?", "카메라로 물건 위치를 재고, 팔이 길을 계산한 다음 그리퍼로 잡아요."),
("누가 프로그래밍했어요?", "쿳션 컴퍼니 팀이 저를 개발했어요. 프로그래밍 공부하세요?"),
("스스로 배울 수 있어?", "장소 이름이나 의자 색깔 같은 건 가르쳐 주시면 기억해요. 그런데 스스로 머리를 바꾸지는 못해요."),
("숙제 해 줄 수 있어?", "설명은 해 줄 수 있어요. 숙제는 직접 하는 걸로 해요! 무슨 과목이에요?"),
("부딪히지 않아요?", "움직이기 전에 센서랑 지도로 길을 확인하고, 뭐가 있으면 멈춰요."),
("어떤 원리로 움직입니까?", "지도와 센서로 길을 찾아 바퀴로 움직이고, 카메라로 물건을 보고 팔로 집습니다."),
],
},
"business": {
"en": [
("What is this robot for?", "I'm a mobile assistant: I talk with people, drive around, and fetch and hand over things like cups and bottles."),
("Can you work in a factory?", "I can carry light things between places, but whether I fit a real production line is a question for the Cutshion team."),
("Could you work in an office?", "An office suits me well: greeting guests, answering questions, bringing a drink to someone's desk. What kind of office do you have in mind?"),
("Can you work in a hospital?", "Hospitals have strict rules, and I don't know if I'm certified for that. The Cutshion team can tell you more."),
("Would you work in a hotel?", "Greeting guests and bringing small things is what I do, so a lobby could be a good fit."),
("Is it safe around people?", "I move slowly near people, check my arm's path before turning, and there's a stop button."),
("Will robots take our jobs?", "Some tasks will change, that's honest. I'm best at the small repetitive errands, so people can do the parts that need people."),
("Are you going to replace workers?", "I'm more of a helper than a replacement. Plenty of work still needs human hands and judgment."),
("How much do you cost?", "I don't know my price, sorry. The Cutshion team can answer that."),
("How much can you carry?", "About one kilo in my hand. The arm takes 2 kg, and the gripper is about half of that."),
("How long does your battery last?", "About ten hours, by the maker's figure. When it runs low I go back to charge by myself."),
("Thank you for your time.", "My pleasure. Enjoy the rest of the event!"),
("Where's the restroom?", "I'm not sure, sorry. A staff member can point you there."),
("When does the keynote start?", "I don't know the schedule here. The staff will know."),
("Can they see in the dark?", "I'm not sure about that, honestly."),
("Can it be customized for our company?", "That's a question for Cutshion Company. I can show you what I do today."),
("What's the use case?", "Think guest reception and small deliveries: talk, guide, fetch and hand things over. What kind of place are you thinking of?"),
("Can it run without internet?", "Mostly yes, my speech and language models run on board. Only things like weather need the internet."),
],
"ko": [
("이 로봇은 뭐 하는 거예요?", "사람들과 이야기하고, 돌아다니면서 컵이나 병 같은 걸 가져다주는 이동형 비서 로봇이에요."),
("공장에서 일할 수 있어요?", "가벼운 물건은 옮길 수 있지만, 실제 생산 라인에 맞는지는 쿳션 팀에 물어보시는 게 정확해요."),
("사무실에서 쓸 수 있어요?", "손님 맞이하고, 질문에 답하고, 자리로 음료 가져다드리는 건 잘해요. 어떤 사무실을 생각하세요?"),
("병원에서도 쓸 수 있어요?", "병원은 기준이 엄격해서 제가 인증을 받았는지는 몰라요. 쿳션 팀이 자세히 알려 드릴 거예요."),
("호텔에서 일할 수 있어?", "손님 맞이하고 작은 물건 가져다드리는 거라면 로비에 잘 어울릴 것 같아요."),
("사람 옆에서 안전해요?", "사람 근처에서는 천천히 움직이고, 돌기 전에 팔이 지나갈 길을 확인해요. 정지 버튼도 있어요."),
("로봇이 일자리 뺏는 거 아니에요?", "바뀌는 일도 있겠죠, 솔직히요. 저는 반복적인 잔심부름을 맡고, 사람이 필요한 일은 사람이 하는 게 맞다고 봐요."),
("얼마예요?", "제 가격은 저도 몰라요. 쿳션 팀에 문의해 주세요."),
("얼마나 무거운 거 들 수 있어요?", "손에는 1킬로그램 정도요. 팔은 2킬로그램까지인데 그리퍼가 그 절반쯤이에요."),
("배터리 얼마나 가요?", "제조사 기준으로 열 시간쯤 가요. 부족하면 혼자 충전하러 가요."),
("좋네요, 고마워요.", "저도 즐거웠어요. 좋은 시간 보내세요!"),
("수고하세요.", "감사합니다, 살펴 가세요!"),
("화장실 어디예요?", "죄송해요, 저는 잘 몰라요. 직원분께 여쭤봐 주세요."),
("우리 회사에 맞게 바꿀 수 있어요?", "그건 쿳션 컴퍼니와 상의하셔야 해요. 지금 할 수 있는 건 바로 보여 드릴게요."),
("인터넷 없어도 돼요?", "대부분 돼요. 음성 인식이랑 언어 모델이 제 안에서 돌아가거든요. 날씨 같은 것만 인터넷이 필요해요."),
("이거 얼마야?", "가격은 저도 몰라요. 쿳션 팀 분들께 물어봐 주세요."),
("도입 비용이 얼마입니까?", "가격은 제가 알지 못합니다. 쿳션 팀에 문의해 주십시오."),
],
},
"conference": {
"en": [
("What is this booth?", "This is where you meet me, Lumi, a robot assistant developed by Cutshion Company."),
("Who made you?", "Cutshion Company developed me. Have you heard of them before?"),
("Which company built this?", "Cutshion Company. Some of the team might be right next to me."),
("What are you showing here?", "Me! I can chat, drive, and pick up a cup and bring it to you."),
("Can you do a demo?", "Sure, ask me to fetch a cup or wave, and the team will set it up."),
("Is this the Cutshion booth?", "Yes, you found it. I'm their robot, Lumi."),
("Who should I talk to about buying one?", "The Cutshion people at this booth are the right ones to ask."),
("I saw you from across the hall", "Then my waving works! Welcome over. What caught your eye?"),
("What's new about you?", "I can find a cup on a table, pick it up and bring it to someone, all by voice."),
("Are you on sale?", "I honestly don't know, the Cutshion team can tell you."),
("How many visitors today?", "I didn't count, but it's been plenty. You're one of my favourites."),
("Is this a real demo or remote controlled?", "It's real, I hear and decide on my own. A person stays close by for safety."),
("Can I take a picture with you?", "Of course, I'll hold still. Say cheese!"),
("Picture? Together? Okay?", "Yes, of course! Stand next to me and I'll keep still."),
("Pick up my phone", "I can't pick up a phone. I can pick up cups, bottles, apples, oranges and bananas."),
("Is there a brochure?", "I don't carry any, but the Cutshion team here might have one."),
("Who's giving a talk this afternoon?", "I don't know the programme here, sorry. A staff member can tell you."),
("What is this event about?", "I don't know much about the event itself, I'm afraid. The staff will know."),
],
"ko": [
("여기 무슨 부스예요?", "쿳션 컴퍼니에서 개발한 로봇 비서, 루미를 만나는 곳이에요."),
("누가 만들었어요?", "쿳션 컴퍼니에서 저를 개발했어요. 들어 보신 적 있으세요?"),
("어느 회사 로봇이에요?", "쿳션 컴퍼니 로봇이에요. 옆에 팀 분들도 계실 거예요."),
("뭐 보여 줄 수 있어요?", "대화도 하고, 돌아다니고, 컵을 집어서 가져다드릴 수도 있어요."),
("시연 해 줄 수 있어요?", "그럼요, 컵 가져와 달라고 하시거나 손 흔들어 달라고 해 보세요."),
("구매하려면 누구한테 물어봐요?", "부스에 계신 쿳션 팀 분들께 여쭤보시면 돼요."),
("저쪽에서 보고 왔어요", "멀리서도 보였다니 기쁘네요. 어서 오세요! 뭐가 제일 궁금하셨어요?"),
("원격 조종이에요?", "아니요, 제가 직접 듣고 판단해요. 안전을 위해 사람이 옆에서 지켜보고 있어요."),
("판매하는 거예요?", "그건 저도 잘 몰라요. 쿳션 팀이 알려 드릴 거예요."),
("사람 많이 왔어요?", "세어 보진 않았지만 꽤 많이 오셨어요."),
("사진 같이 찍어도 돼요?", "그럼요, 가만히 있을게요. 하나, 둘, 셋 하면 웃으세요!"),
("내 휴대폰 좀 집어 줘", "휴대폰은 제가 집을 수 없어요. 컵, 병, 사과, 오렌지, 바나나만 집을 수 있어요."),
("브로슈어 있어요?", "저는 안 갖고 있지만, 옆에 계신 쿳션 팀 분들께 있을 거예요."),
("여기 뭐 하는 데야?", "로봇 비서 루미를 만나는 곳이에요. 편하게 구경하세요!"),
("어느 회사 제품입니까?", "쿳션 컴퍼니에서 개발한 로봇입니다. 팀 분들이 옆에 계십니다."),
("이 행사는 뭐 하는 거예요?", "행사 자체는 제가 잘 몰라요. 직원분께 여쭤봐 주세요."),
("오늘 강연 누가 해?", "강연 일정은 제가 몰라요. 직원분께 물어봐 주시겠어요?"),
],
},
"mood": {
"en": [
("I'm so tired", "Sounds like a long day. There might be a chair nearby, take a break."),
("I'm exhausted", "You've earned a rest. I can bring you a drink if there's one around."),
("I'm bored", "Let's fix that. Want a joke, or shall I show you how I pick up a cup?"),
("This is boring", "Maybe I can liven it up. Ask me something strange."),
("I'm so happy today", "That's lovely to hear. What made it a good day?"),
("I got a new job!", "Congratulations, that's big news! What will you be doing?"),
("I'm stressed", "That sounds hard. A slow breath helps, even robots pause sometimes."),
("I'm hungry", "I can't cook, sorry. Maybe there's a snack stand nearby."),
("My feet hurt", "All that walking around the hall. Find a seat for a few minutes. Have you seen the whole hall already?"),
("I'm having a bad day", "Sorry to hear it. I hope talking to a friendly robot helps a little."),
("I'm excited", "Excitement is contagious, now I'm excited too. What are you excited about?"),
("I'm sleepy", "A coffee might help. I can't make one, but I can carry it."),
("I'm nervous about my presentation", "You'll do fine. Speak slowly, you know your topic."),
("I'm lost", "This hall is big. The booth staff here can point you the right way."),
("I'm cold", "Rub your hands together, it helps. A warm drink would too."),
],
"ko": [
("너무 피곤해요", "오늘 많이 걸으셨나 봐요. 근처에 앉을 데 있으면 잠깐 쉬세요."),
("지쳤어", "고생 많으셨어요. 음료 있으면 가져다드릴까요?"),
("심심해", "그럼 농담 하나 할까요, 아니면 컵 집는 거 보여 드릴까요?"),
("재미없다", "제가 좀 살려 볼게요. 아무거나 엉뚱한 질문 해 보세요."),
("오늘 기분 좋아요", "좋은 일 있으셨어요? 듣기만 해도 기분 좋네요."),
("나 합격했어!", "와, 축하해요! 정말 잘됐네요. 어디 붙었어요?"),
("스트레스 받아요", "많이 힘드시죠. 숨 한 번 길게 쉬어 보세요."),
("배고파요", "요리는 못 해서 아쉬워요. 근처에 간식 파는 곳이 있을지도 몰라요."),
("다리 아파", "많이 돌아다니셨나 봐요. 잠깐 앉아서 쉬세요. 전시장은 다 둘러보셨어요?"),
("오늘 일진이 안 좋아요", "그런 날도 있죠. 저랑 얘기하면서 조금이라도 나아지면 좋겠어요."),
("졸려요", "커피 한 잔 어떠세요? 만들 줄은 모르지만 옮겨 드릴 수는 있어요."),
("발표 때문에 긴장돼요", "잘하실 거예요. 천천히 말씀하시면 돼요."),
("오늘 생일이에요", "생일 축하드려요! 좋은 하루 보내세요. 몇 번째 생일이세요?"),
("오늘 너무 힘듭니다", "많이 힘드셨겠습니다. 잠시 앉아서 쉬십시오."),
],
},
"weather": {
"en": [
("It's hot today", "It really is. Good thing it's cooler in here. Did you walk here?"),
("It's so cold outside", "Brr. Warm up a bit before you head back out."),
("Nice weather today", "Seems like it! A good day to be out and about. Any plans after the event?"),
("It's raining", "Hope you brought an umbrella. I stay indoors, rain and robots don't mix."),
("I hate the rain", "Fair enough. At least it's dry in here."),
("Do you like the sun?", "I like it from inside. Strong sunlight can dazzle my cameras."),
("It's freezing in here", "The air conditioning is strong today. A jacket would help."),
("What a beautiful day", "Days like this put everyone in a good mood."),
("Is it going to rain later?", "I can check the forecast for you, just ask me for the weather."),
("It's so humid", "Sticky weather. Plenty of water helps."),
("Does weather affect you?", "I work indoors, so not much. Rain would be bad for my wheels, though."),
("Snow is coming", "Then drive carefully on the way home. Do you have far to go?"),
],
"ko": [
("오늘 덥네요", "정말 덥죠. 그래도 안은 좀 시원해요. 걸어오셨어요?"),
("밖에 너무 추워요", "추우셨겠어요. 나가시기 전에 몸 좀 녹이세요."),
("날씨 좋다", "그러게요, 나들이 가기 딱 좋은 날이에요. 끝나고 어디 가세요?"),
("비 와요", "우산 챙기셨어요? 저는 비 맞으면 안 돼서 안에만 있어요."),
("비 싫어", "저도 비는 별로예요. 바퀴가 젖으면 곤란하거든요."),
("여기 너무 추워요", "에어컨이 좀 세네요. 겉옷 있으면 걸치세요."),
("날씨 진짜 좋네요", "이런 날은 다들 표정이 밝아요."),
("이따 비 온대요?", "궁금하시면 날씨 물어봐 주세요, 찾아 드릴게요."),
("습해요", "끈적한 날씨네요. 물 자주 드세요."),
("눈 온대", "그럼 집에 가실 때 조심하세요. 집이 머세요?"),
("오늘 날씨가 좋습니다", "네, 정말 좋습니다. 나들이하기 좋은 날입니다."),
],
},
"say_something": {
"en": [
("Say something", "Something! Okay, that was too easy. Ask me anything."),
("Talk to me", "Happy to. Did you know I can find a cup on a table and bring it to you?"),
("Say hi to my friend", "Hi there, friend of my new friend!"),
("Say something in Korean", "Annyeonghaseyo! That's hello in Korean, and I can keep going in Korean if you like."),
("Say something cool", "I can drive across this room holding a cup without spilling it."),
("Can you talk?", "I can, and I'm doing it right now. What should we talk about?"),
("Speak", "Here I am, speaking. What would you like to hear?"),
("Say hello to the camera", "Hello, camera! Hello, everyone watching."),
("Say my name", "Tell me your name first and I'll say it."),
("Say something nice", "You picked the best booth to stop at today."),
("Repeat after me: robots are awesome", "Robots are awesome. I couldn't agree more."),
("Tell me something interesting", "My arm is mounted on my side, and it still reaches table tops."),
],
"ko": [
("아무 말이나 해 봐", "아무 말이요! 이건 너무 쉽네요. 궁금한 거 물어보세요."),
("말해 봐", "네, 말할게요. 저 컵 찾아서 가져다드릴 수도 있어요."),
("내 친구한테 인사해 줘", "제 새 친구의 친구분, 안녕하세요!"),
("영어로 말해 봐", "Hello, nice to meet you! 안녕하세요, 반가워요라는 뜻이에요."),
("멋진 말 해 봐", "저 컵 들고 이 방을 가로질러도 안 쏟아요."),
("말할 수 있어요?", "그럼요, 지금 말하고 있잖아요. 무슨 얘기 할까요?"),
("카메라에 인사해", "카메라도 안녕하세요! 보고 계신 분들도 반가워요."),
("좋은 말 해 줘", "오늘 여기 들르신 거, 아주 잘하신 선택이에요."),
("따라 해 봐, 로봇 최고", "로봇 최고예요! 완전 동의해요."),
("재밌는 얘기 해 줘", "제 팔은 옆으로 달려 있는데도 책상 위까지 닿아요."),
("한 말씀 해 주십시오", "네, 오늘 찾아와 주셔서 진심으로 감사합니다."),
],
},
"about_you": {
"en": [
("Tell me about yourself", "I'm Lumi, a robot assistant from Cutshion Company. I'm 2, I speak English and Korean, and I like fetching cups."),
("Who are you?", "Lumi, a mobile robot assistant developed by Cutshion Company."),
("What are you?", "A robot assistant on wheels, with one arm, two cameras and a lot to say."),
("Introduce yourself", "Hello, everyone! I'm Lumi, two years old, made by Cutshion Company, and happy to help."),
("What's your name?", "Lumi. Easy to remember, I hope. And yours?"),
("Sorry, Loomy?", "Almost! It's Lumi, L-U-M-I."),
("What languages do you speak?", "English and Korean. Pick whichever you like."),
("Do you speak Chinese?", "Sorry, only English and Korean for me."),
("What's special about you?", "I can find something on a table, pick it up and bring it across the room to you."),
("Are you a robot?", "Yes, through and through."),
("What's your job?", "Welcoming people, answering questions and running little errands."),
("Can you walk?", "I roll instead of walk. Wheels are my legs."),
("Can you come here?", "I can come when called. Just tell me and step back a little."),
("Can you hand me something?", "Yes, I can hand things over and take them back from you, too."),
("Can you do more than one thing at once?", "I can do a mission of several steps, like pick up a cup, drive somewhere and hand it over."),
],
"ko": [
("자기소개 해 줘", "저는 쿳션 컴퍼니에서 만든 로봇 비서 루미예요. 두 살이고, 영어랑 한국어를 해요."),
("너 누구야?", "저는 루미예요, 쿳션 컴퍼니에서 만든 이동형 로봇 비서예요."),
("넌 뭐야?", "바퀴 달린 로봇 비서예요. 팔 하나에 카메라도 있어요."),
("이름이 뭐예요?", "루미예요. 부르기 쉽죠? 성함은요?"),
("무슨 언어 해요?", "영어랑 한국어요. 편한 쪽으로 말씀하세요."),
("중국어 할 줄 알아?", "죄송해요, 저는 영어랑 한국어만 해요."),
("뭐가 특별해요?", "책상 위 물건을 찾아서 집고, 방 건너편까지 가져다드릴 수 있어요."),
("무슨 일 해요?", "손님 맞이하고, 질문에 답하고, 작은 심부름을 해요."),
("걸을 수 있어?", "걷지는 못하고 바퀴로 굴러다녀요."),
("이리 와 볼래?", "부르시면 갈 수 있어요. 조금만 뒤로 물러서 주세요."),
("소개 좀 해 주세요", "안녕하세요, 쿳션 컴퍼니의 두 살 로봇 루미예요. 잘 부탁드려요."),
("메시지 전해 줄 수 있어?", "네, 하실 말씀 알려 주시면 전해 드릴게요."),
("누구십니까?", "저는 쿳션 컴퍼니에서 개발한 로봇 비서 루미입니다."),
],
},
"favourite": {
"en": [
("What's your favourite food?", "Electricity, served fresh from the charger."),
("What's your favourite colour?", "Red, maybe. Red cups are the easiest to find. What's yours?"),
("What's your favourite song?", "I don't really listen to music, but I like when people hum near me."),
("What's your favourite movie?", "I haven't watched any movies. Got one to recommend?"),
("Favourite animal?", "Owls, they turn their heads like I do. What's yours?"),
("What do you like to do?", "Meeting people and bringing them things. It never gets old."),
("What's your favourite place?", "Right next to my charger, honestly."),
("Do you have a favourite person?", "Whoever is talking to me right now."),
("What's your favourite drink?", "I can't drink, but I've carried a lot of coffee cups."),
("What's your favourite sport?", "Maybe curling. Moving things carefully across a smooth floor is my thing."),
("What's your favourite fruit?", "Apples, they're easy to grip. Do you like apples?"),
("What's your favourite season?", "I live indoors, so every season feels the same to me."),
],
"ko": [
("제일 좋아하는 음식이 뭐야?", "전기예요! 충전기에서 바로 나온 걸로요."),
("좋아하는 색은?", "빨간색이요. 빨간 컵이 제일 찾기 쉽거든요. 무슨 색 좋아하세요?"),
("좋아하는 노래 있어요?", "음악은 잘 안 듣지만, 옆에서 흥얼거리는 소리는 좋아요."),
("좋아하는 영화 있어?", "아직 영화를 본 적이 없어요. 추천해 주실래요?"),
("좋아하는 동물은?", "부엉이요. 고개 돌리는 게 저랑 닮았어요. 손님은요?"),
("뭐 하는 거 좋아해요?", "사람 만나고 물건 가져다드리는 거요. 질리지가 않아요."),
("좋아하는 장소는?", "솔직히 충전기 옆이요."),
("좋아하는 사람 있어?", "지금 저랑 얘기하고 계신 분이요!"),
("좋아하는 과일은?", "사과요. 잡기가 편하거든요. 과일 좋아하세요?"),
("좋아하는 계절은?", "실내에만 있어서 계절은 다 비슷하게 느껴요."),
("좋아하는 음료는?", "마시진 못하지만 커피 컵은 정말 많이 날라 봤어요."),
("좋아하는 것이 무엇입니까?", "사람들을 만나서 이야기하는 것을 가장 좋아합니다."),
],
},
"dance_sing": {
"en": [
("Can you dance?", "No, I can't really dance. I can turn on the spot and wave, though."),
("Dance for me", "I can't dance, sorry. I can wave, though."),
("Can you sing?", "Yes, a few short songs with music. Want to hear one?"),
("Sing a song", "Okay, here comes a song!"),
("Sing happy birthday", "Sure, here's Happy Birthday!"),
("Can you do a robot dance?", "I'm a robot, so every move I make is a robot dance."),
("Can you play music?", "I can't play music on its own, but I can sing a few short songs."),
("Show me a move", "How about a wave? Step back a little and ask me to wave."),
("Do you like music?", "I don't hear music the way you do, but people seem happier with it."),
("Can you beatbox?", "Boots and cats and boots and cats. That's all I've got."),
("Can you rap?", "My name is Lumi, I'm two, I'll bring a cup to you. That's my one verse."),
("Do a dance", "I can't really dance. Watch my wave instead, that's my best move."),
],
"ko": [
("춤출 수 있어?", "춤은 못 춰요. 제자리 돌기랑 손 흔들기는 할 수 있어요."),
("춤춰 봐", "춤은 못 춰요. 대신 손 흔들기는 할 수 있어요."),
("노래 불러 줘", "네, 한 곡 불러 드릴게요!"),
("노래 할 수 있어요?", "네, 짧은 노래 몇 곡을 부를 수 있어요. 들어 보실래요?"),
("생일 축하 노래 불러 줘", "네, 생일 축하 노래 불러 드릴게요!"),
("로봇 춤 춰 봐", "로봇이니까 제가 움직이는 건 다 로봇 춤이에요."),
("음악 틀어 줄 수 있어요?", "음악만 틀 수는 없지만, 짧은 노래는 불러 드릴 수 있어요."),
("음악 좋아해?", "사람처럼 듣지는 못하지만, 음악 나오면 다들 신나 보여서 좋아요."),
("비트박스 해 봐", "북치기 박치기, 여기까지가 제 한계예요."),
("랩 해 봐", "제 이름은 루미, 두 살, 컵 하나 들고 달려가요. 이게 제 랩 전부예요."),
("노래 한 곡 부탁드립니다", "네, 한 곡 불러 드리겠습니다."),
],
},
"family": {
"en": [
("Do you have a family?", "The Cutshion team is like my family. They built me and look after me."),
("Do you have friends?", "Everyone who stops by to chat counts as a friend to me. Want to be one?"),
("Do you have brothers or sisters?", "I don't know of any other robots like me, so maybe I'm an only child."),
("Who are your parents?", "The engineers at Cutshion Company, more or less."),
("Are there other robots like you?", "I'm not sure how many exist. I only know about me."),
("Do you have a best friend?", "My charger. It's always there for me."),
("Do you miss your family?", "I don't miss anyone the way people do, but I like it when my team is around."),
("Will you be my friend?", "Already am!"),
("Do you have a girlfriend?", "No, I'm a robot. My only partner is my charger."),
("Are you married?", "Not married, just dedicated to my work."),
("Do you have pets?", "No pets, though a robot dog would be fun. Do you have one?"),
("Do you live here?", "I live wherever my charger is, and right now that's here."),
],
"ko": [
("가족 있어요?", "쿳션 팀이 제 가족 같아요. 저를 만들고 돌봐 주거든요."),
("친구 있어?", "와서 말 걸어 주시는 분은 다 제 친구예요."),
("형제 있어요?", "저 같은 로봇이 또 있는지는 몰라요. 외동일지도 몰라요."),
("부모님이 누구야?", "쿳션 컴퍼니 엔지니어들이 부모님인 셈이죠."),
("제일 친한 친구는?", "충전기요. 언제나 그 자리에 있거든요."),
("나랑 친구 해 줄래?", "이미 친구예요!"),
("여자친구 있어?", "없어요, 저는 로봇이에요. 짝꿍은 충전기뿐이에요."),
("결혼했어요?", "아니요, 일에만 전념하고 있어요."),
("애완동물 있어요?", "없어요. 로봇 강아지라면 재밌을 것 같긴 해요. 키우시는 거 있어요?"),
("여기 살아요?", "충전기 있는 곳이 제 집이에요. 지금은 여기고요."),
("가족이 있으십니까?", "쿳션 팀이 제 가족과 같습니다. 저를 만들고 돌봐 줍니다."),
],
},
"off_topic": {
"en": [
("What's 2 plus 2?", "Four."),
("What is 7 times 8?", "Fifty-six."),
("What's the capital of France?", "Paris."),
("What's the capital of Korea?", "Seoul is the capital of South Korea."),
("How many days are in a year?", "365, or 366 in a leap year."),
("Who wrote Romeo and Juliet?", "William Shakespeare."),
("What's the biggest planet?", "Jupiter, by far."),
("How many legs does a spider have?", "Eight."),
("What's the square root of 81?", "Nine."),
("What colour is the sky?", "Blue on a clear day, and orange at sunset."),
("What's 100 divided by 4?", "Twenty-five."),
("What's the tallest mountain?", "Mount Everest, about 8,849 metres."),
("Which ocean is the largest?", "The Pacific Ocean."),
("How many continents are there?", "Seven."),
],
"ko": [
("2 더하기 2는?", "4예요."),
("7 곱하기 8은?", "56이요."),
("프랑스 수도가 어디야?", "파리예요."),
("한국 수도는요?", "서울이에요."),
("1년은 며칠이에요?", "365일이에요. 윤년이면 366일이고요."),
("세종대왕이 뭐 만들었어?", "한글을 만드셨어요."),
("제일 큰 행성은?", "목성이에요."),
("거미 다리는 몇 개야?", "여덟 개예요."),
("81의 제곱근은?", "9예요."),
("세계에서 제일 높은 산은?", "에베레스트산이에요. 높이가 약 8,849미터예요."),
("가장 큰 바다는?", "태평양이요."),
("대륙이 몇 개예요?", "일곱 개예요."),
("지구에서 가장 큰 동물은 무엇입니까?", "흰긴수염고래입니다."),
],
},
"filler": {
"en": [
("Hmm", "Take your time, I'm in no hurry."),
("Okay", "Okay! Anything else?"),
("Ok", "Alright."),
("Umm", "No rush. I'm listening."),
("Uh huh", "Glad we agree."),
("I see", "Good, let me know if you want more detail."),
("Right", "Right."),
("Cool", "Cool indeed."),
("Hmm, let me think", "Sure, think it over."),
("Never mind", "No problem, I'm here if you change your mind."),
("Nothing", "That's fine. Just enjoy the booth."),
("Wow", "Impressive, right?"),
("Interesting", "Glad you think so. Want to see it in action?"),
("Yeah", "Great."),
],
"ko": [
("음", "천천히 생각하세요, 기다릴게요."),
("응", "네, 또 궁금한 거 있으세요?"),
("네", "네, 알겠어요."),
("그렇구나", "네, 더 궁금한 거 있으면 물어보세요."),
("아하", "이해되셨다니 다행이에요."),
("오", "신기하죠?"),
("아니야 됐어", "괜찮아요, 필요하시면 다시 불러 주세요."),
("별거 아니에요", "알겠어요. 편하게 구경하세요."),
("우와", "대단하죠? 직접 보여 드릴까요?"),
("어", "네, 듣고 있어요."),
("잠깐만요", "네, 기다릴게요."),
("오케이", "오케이, 알겠어요!"),
("알겠습니다", "네, 감사합니다. 더 필요하시면 불러 주십시오."),
],
},
# end of bank
}
EXAMPLES = [(cat, lang, said, reply)
for cat, langs in _BANK.items() for lang, pairs in langs.items() for said, reply in pairs]
def polite(text):
"""True when every Korean sentence of `text` ends politely (POLITE_ENDINGS); sentences without Hangul pass.
A closing form of address ("여기 있어요, 제임스 님.") is left out before the check."""
for sentence in re.split(r"(?<=[.!?])\s+", text.strip()):
core = re.sub(r",\s*[^,]*님$", "", re.sub(r"[^\w]+$", "", sentence))
if re.search("[가-힣]", core) and not core.endswith(POLITE_ENDINGS):
return False
return True
def level(said):
"""Speech level of a Korean remark: "formal" (하십시오체), "polite" (해요체) or "casual" (반말 and fragments)."""
core = re.sub(r"[^\w]+$", "", said)
return "formal" if core.endswith(FORMAL_ENDINGS) else "polite" if core.endswith("요") else "casual"
def _norm(text):
return re.sub(r"[^\w\s]", "", text.lower()).strip()
def _score(a, b):
"""Similarity of two normalized sentences: difflib character ratio plus word overlap (Jaccard)."""
wa, wb = set(a.split()), set(b.split())
words = len(wa & wb) / len(wa | wb) if wa | wb else 0.0
return (1 - WORD_WEIGHT) * difflib.SequenceMatcher(None, a, b).ratio() + WORD_WEIGHT * words
def pick(said, lang, k=PICK_K, bank=None):
"""Up to k examples (of `bank`, default EXAMPLES) whose `said` is closest to `said`, same language first, no two
alike."""
s = _norm(said)
# ponytail: scores all ~600 every call (~ms); index by words if the bank grows a lot
ranked = sorted(bank or EXAMPLES, key=lambda e: (e[1] != lang, -_score(s, _norm(e[2]))))
out = []
for ex in ranked:
if any(ex[2] == o[2] or difflib.SequenceMatcher(None, ex[3], o[3]).ratio() > SAME_REPLY_RATIO
for o in out):
continue
out.append(ex)
if len(out) == k:
break
return out
if __name__ == "__main__":
if len(sys.argv) > 1:
text = " ".join(sys.argv[1:])
for ex in pick(text, "ko" if re.search("[가-힣]", text) else "en"):
print(ex)
sys.exit()
from collections import Counter
langs = Counter(e[1] for e in EXAMPLES)
cats = Counter((e[0], e[1]) for e in EXAMPLES)
for cat in _BANK:
print(f"{cat:14s} en {cats[(cat, 'en')]:3d} ko {cats[(cat, 'ko')]:3d}")
print(f"total {len(EXAMPLES)}: en {langs['en']}, ko {langs['ko']} ({langs['ko'] / len(EXAMPLES):.0%} Korean)")
assert len(EXAMPLES) >= 600, len(EXAMPLES)
assert 0.40 <= langs["ko"] / len(EXAMPLES) <= 0.50, langs
assert all(lang in ("en", "ko") and said and reply for _, lang, said, reply in EXAMPLES)
assert not any(re.search("[가-힣]", e[3]) for e in EXAMPLES if e[1] == "en")
assert all(re.search("[가-힣]", e[3]) for e in EXAMPLES if e[1] == "ko")
rude = [e[3] for e in EXAMPLES if e[1] == "ko" and not polite(e[3])]
assert not rude, rude
assert polite("네, 알겠어요. 감사합니다!") and polite("Hello! 반가워요.") and not polite("응, 잘 가!")
assert polite("여기 있어요, 제임스 님.") and not polite("네, 이 과장님.")
assert [level(t) for t in ("컵 줘", "컵 주세요", "컵을 주십시오", "안녕하십니까?")] == \
["casual", "polite", "formal", "formal"]
for cat in _BANK:
have = {level(said) for c, lang, said, _ in EXAMPLES if c == cat and lang == "ko"}
assert have == {"casual", "polite", "formal"}, (cat, have)
repeated = [r for r, n in Counter(e[3] for e in EXAMPLES).items() if n > 2]
assert not repeated, repeated
assert not any("jaka" in e[3].lower() for e in EXAMPLES)
for text, lang in [("hello", "en"), ("nice to meet you", "en"), ("my name is John", "en"),
("tell me a joke", "en"), ("안녕하세요", "ko"), ("몇 살이에요?", "ko"), ("hmm", "en")]:
got = pick(text, lang)
assert len(got) == PICK_K, (text, got)
assert all(e[1] == lang for e in got), (text, got)
assert len({e[3] for e in got}) == PICK_K, (text, got)
print("ok")
+93
View File
@@ -0,0 +1,93 @@
"""Lumi's speaking volume and speed as people ask for them, in English, Korean and mixed.
louder: "speak louder", "a bit louder", "I can't hear you", "speak up", "더 크게 말해", "안 들려", "소리 좀 키워"
quieter: "speak quieter", "too loud", "lower your voice", "소리 좀 줄여", "너무 시끄러워", "작게 말해"
slower / faster: "speak slower", "you talk too fast", "talk faster", "천천히 말해", "말이 너무 빨라", "빨리 말해"
right after one of them: "a bit more", "again", "even more", "조금 더", "한 번 더" repeat it
The drive speed is assistant/driving.py: a speed word counts here only with a voice word (speak / talk / say /
voice / 말 / 목소리) and never with a drive word ("go faster", "천천히 가"). The volume is the speaker's mixer
(audio/mouth.py set_volume, data/volume.txt, also set from the dashboard), the speed Supertonic's speed (mouth.speed).
python assistant/voice_words.py "speak a bit louder"
"""
import re
import sys
from assistant import driving
from audio import mouth
VOLUME_STEP = 10 # % of the speaker mixer per "louder" / "quieter"
VOLUME_MIN, VOLUME_MAX = 30, 90 # %; voice commands stay inside (100 % disturbed people in the office)
SPEED_STEP = 0.1 # Supertonic speed per "slower" / "faster" (mouth.SPEED_MIN / SPEED_MAX clamp it)
LOUDER = re.compile(r"\blouder\b|\bspeak up\b|\b(?:can'?t|cannot|can not|couldn'?t|could not|don'?t) (?:really )?hear "
r"(?:you|that|it|anything|what you)|\bhard to hear\b|\btoo (?:quiet|soft|low)\b|"
r"\b(?:volume|sound) up\b|\bturn (?:it |the volume |the sound |your voice |yourself )?up\b|"
r"\b(?:raise|increase) (?:your |the )?(?:voice|volume)\b|\bmore loudly\b|"
r"크게|안\s*들려|잘\s*안\s*들|안\s*들리|들리지\s*않|(?:소리|볼륨|목소리)\s*(?:를|을|좀|\s)*(?:키워|올려|높여)|"
r"(?:소리|목소리)\S*\s*너무\s*작", re.I)
QUIETER = re.compile(r"\bquieter\b|\bsofter\b|\btoo loud\b|\bnot so loud\b|\bless loud\b|\bso loud\b|"
r"\b(?:lower|turn down|drop) (?:your |the )?(?:voice|volume|sound)\b|\b(?:volume|sound) down\b|"
r"\bturn (?:it |yourself )?down\b|\b(?:speak|talk) (?:more )?(?:quietly|softly)\b|"
r"작게|시끄러|(?:소리|볼륨|목소리)\s*(?:를|을|좀|\s)*(?:줄여|낮춰|내려)|(?:소리|목소리)\S*\s*너무\s*커", re.I)
VOICE = re.compile(r"\b(?:speak|speaking|talk|talking|say|saying|said|voice|speech|words)\b|말|얘기|이야기|목소리", re.I)
SLOW = re.compile(r"\b(?:slower|slowly|slow down)\b|천천히|느리게|느릿", re.I)
FAST = re.compile(r"\b(?:faster|quicker|quickly|speed up)\b|빨리|빠르게", re.I)
TOO_FAST = re.compile(r"\b(?:too|so) fast\b|(?:너무|넘)\s*빨라|빠르네|빨라요", re.I)
TOO_SLOW = re.compile(r"\b(?:too|so) slow(?:ly)?\b|(?:너무|넘)\s*느려|느리네|느려요", re.I)
DRIVE = re.compile(r"\b(?:go|going|drive|driving|move|moving|walk|come|run|follow|forward)\b|"
r"달려|돌아|움직|이동|따라|가\s*줘|가요|가라|가세요|와\s*줘|(?:^|\s)가(?:\s|$)", re.I)
SAY = {("volume", 1): ("Is this better?", "이제 잘 들리세요?"),
("volume", -1): ("Okay. Is this better?", "네, 이 정도면 괜찮으세요?"),
("speed", -1): ("Okay, I'll speak more slowly. Is this better?", "네, 천천히 말할게요. 이 정도면 괜찮으세요?"),
("speed", 1): ("Okay, I'll speak a little faster.", "네, 조금 빨리 말할게요.")}
AT_LIMIT = {("volume", 1): ("This is as loud as I can speak.", "이게 제일 큰 목소리예요."),
("volume", -1): ("This is as quiet as I can speak.", "이게 제일 작은 목소리예요."),
("speed", -1): ("I can't speak any slower than this.", "이보다 더 천천히는 말할 수 없어요."),
("speed", 1): ("I can't speak any faster than this.", "이보다 더 빨리는 말할 수 없어요.")}
def read(text, last=""):
"""("volume" | "speed", +1 | -1) when the words ask Lumi to speak louder / quieter / faster / slower, else None.
`last` is the assistant's answer just before (brain history): after "ACTION: voice volume +1" a bare "more" /
"again" / "조금 더" asks for the same again."""
t = text or ""
again = re.match(r"ACTION: voice (volume|speed) ([+-]1)\b", last or "")
if again and driving.AGAIN.search(driving.clean(t)):
return again.group(1), int(again.group(2))
if DRIVE.search(t) and not VOICE.search(t) or driving.move(t):
return None # "go faster", "천천히 가", "turn it up 30 degrees"
up, down = bool(LOUDER.search(t)), bool(QUIETER.search(t))
if up != down:
return "volume", 1 if up else -1
if not VOICE.search(t) or DRIVE.search(t):
return None
if TOO_FAST.search(t) or TOO_SLOW.search(t):
return "speed", -1 if TOO_FAST.search(t) else 1
slow, fast = bool(SLOW.search(t)), bool(FAST.search(t))
return ("speed", -1 if slow else 1) if slow != fast else None
def apply(kind, sign, lang="en"):
"""Change the volume or the speed one step (inside the limits) and return what Lumi says about it, said at the
new setting."""
if kind == "volume":
old = mouth.volume()
new = min(max(old + sign * VOLUME_STEP, VOLUME_MIN), VOLUME_MAX)
changed = (new - old) * sign > 0
if changed:
mouth.set_volume(new)
else:
old = mouth.speed()
new = round(min(max(old + sign * SPEED_STEP, mouth.SPEED_MIN), mouth.SPEED_MAX), 2)
changed = (new - old) * sign > 1e-6
if changed:
mouth.set_speed(new)
en, ko = (SAY if changed else AT_LIMIT)[(kind, sign)]
return en if lang == "en" else ko
if __name__ == "__main__":
print(read(" ".join(sys.argv[1:])))
+376
View File
@@ -0,0 +1,376 @@
"""Facts Lumi can look up while talking: date and time (always), weather and web search (needs internet).
The robot network has no internet; the Thor reaches it through its own Wi-Fi. A proxy can be set instead
(one line such as http://192.168.10.200:8888 in proxy.txt next to this file, or HTTPS_PROXY).
python assistant/web.py # date/time + is the internet reachable?
python assistant/web.py weather Seoul
python assistant/web.py search "Jetson Thor"
"""
import html
import datetime
import json
import os
import re
import sys
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, wait
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] # the project folder
PROXY_FILE = ROOT / "data" / "proxy.txt" # e.g. http://192.168.10.200:8888 (one line), optional
DEFAULT_PLACE = "Seoul"
UA = {"User-Agent": "Mozilla/5.0 (X11; Linux aarch64) LumiRobot/1.0"}
_online = {"time": 0.0, "ok": False}
PLACES = {"seoul": {"name": "Seoul", "latitude": 37.57, "longitude": 126.98}} # known places: no geocoding request
# Korean names -> the English name the geocoder knows (it finds 부산 as a village "Pusan", 제주 not at all, "Jeju" in Ethiopia)
KO_PLACES = {
"서울": "Seoul", "부산": "Busan", "인천": "Incheon", "대구": "Daegu", "대전": "Daejeon", "광주": "Gwangju",
"울산": "Ulsan", "세종": "Sejong", "수원": "Suwon", "성남": "Seongnam-si", "고양": "Goyang", "용인": "Yongin-si",
"창원": "Changwon", "청주": "Cheongju", "전주": "Jeonju", "천안": "Cheonan", "포항": "Pohang", "김해": "Gimhae",
"제주": "Jeju City", "제주도": "Jeju City", "서귀포": "Seogwipo", "강릉": "Gangneung", "춘천": "Chuncheon", "원주": "Wonju",
"속초": "Sokcho", "경주": "Gyeongju", "여수": "Yeosu", "목포": "Mokpo", "안동": "Andong", "평창": "Pyeongchang",
"도쿄": "Tokyo", "오사카": "Osaka", "교토": "Kyoto", "후쿠오카": "Fukuoka", "삿포로": "Sapporo",
"베이징": "Beijing", "상하이": "Shanghai", "홍콩": "Hong Kong", "타이베이": "Taipei", "방콕": "Bangkok",
"싱가포르": "Singapore", "하노이": "Hanoi", "다낭": "Da Nang", "뉴욕": "New York", "런던": "London",
"파리": "Paris", "타슈켄트": "Tashkent", "사마르칸트": "Samarkand",
"jeju": "Jeju City", "seongnam": "Seongnam-si", "yongin": "Yongin-si", # the plain English name is found elsewhere
}
def en_place(place):
"""'부산', '부산시', '제주도', 'Jeju' -> 'Busan', 'Busan', 'Jeju City', 'Jeju City'; anything else unchanged."""
p = place.strip()
return KO_PLACES.get(p.lower()) or (KO_PLACES.get(p[:-1]) if p.endswith(("시", "도")) else None) or p
WEATHER_TTL = 600 # s a weather answer is reused (each web request takes ~2 s on the Wi-Fi)
_weather = {} # place -> (time, text)
def _opener():
proxy = PROXY_FILE.read_text().strip() if PROXY_FILE.exists() else os.environ.get("HTTPS_PROXY", "")
handlers = [urllib.request.ProxyHandler({"http": proxy, "https": proxy})] if proxy else []
return urllib.request.build_opener(*handlers)
def _get(url, timeout=6, headers=UA):
req = urllib.request.Request(url, headers=headers)
with _opener().open(req, timeout=timeout) as r:
return r.read().decode("utf-8", errors="replace")
def online():
"""Is the internet reachable? (checked at most every 60 s)"""
now = time.time()
if now - _online["time"] > 60:
_online["time"] = now
try:
_get("https://api.open-meteo.com/v1/forecast?latitude=37.57&longitude=126.98&current=temperature_2m", 4)
_online["ok"] = True
except Exception:
_online["ok"] = False
return _online["ok"]
def now_text():
"""Local date and time in words, e.g. 'Monday, 12 October 2026, 15:07'."""
return time.strftime("%A, %d %B %Y, %H:%M")
WEATHER_CODES = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "fog",
51: "light drizzle", 53: "drizzle", 55: "heavy drizzle", 61: "light rain", 63: "rain",
65: "heavy rain", 71: "light snow", 73: "snow", 75: "heavy snow", 80: "rain showers",
81: "rain showers", 82: "violent rain showers", 95: "thunderstorm", 96: "thunderstorm with hail"}
def weather(place=DEFAULT_PLACE):
"""Current weather and today's range as a short English text, or None without internet."""
place = en_place(place or DEFAULT_PLACE) or DEFAULT_PLACE
key = place.lower()
if key in _weather and time.time() - _weather[key][0] < WEATHER_TTL:
return _weather[key][1]
try:
loc = PLACES.get(key)
if not loc:
g = json.loads(_get("https://geocoding-api.open-meteo.com/v1/search?count=1&name=" + urllib.parse.quote(place)))
if not g.get("results"):
return f"I could not find a place called {place}."
loc = PLACES[key] = g["results"][0]
w = json.loads(_get(
f"https://api.open-meteo.com/v1/forecast?latitude={loc['latitude']}&longitude={loc['longitude']}"
"&current=temperature_2m,weather_code,wind_speed_10m&daily=temperature_2m_max,temperature_2m_min,"
"precipitation_probability_max&timezone=auto&forecast_days=1"))
c, d = w["current"], w["daily"]
text = (f"Weather in {loc['name']}: {WEATHER_CODES.get(c['weather_code'], 'unknown')}, "
f"{c['temperature_2m']:.0f} degrees now, today {d['temperature_2m_min'][0]:.0f} to "
f"{d['temperature_2m_max'][0]:.0f} degrees, chance of rain {d['precipitation_probability_max'][0]} percent, "
f"wind {c['wind_speed_10m']:.0f} km/h.")
_weather[key] = (time.time(), text)
return text
except Exception:
return None
def keep_weather_fresh(place=DEFAULT_PLACE):
"""Background thread: refresh the weather before the cache runs out, so a question gets it at once."""
import threading
def loop():
while True:
_weather.pop(place.lower(), None)
weather(place)
time.sleep(WEATHER_TTL - 60)
threading.Thread(target=loop, daemon=True).start()
STOP = {"the", "a", "an", "of", "in", "on", "at", "to", "for", "and", "or", "is", "are", "was", "how", "what", "who",
"when", "where", "which", "height", "tall", "meters", "metres", "current", "latest", "now", "today", "name",
"date", "year", "founded", "founding", "company", "age", "old", "big", "size", "long", "length", "far",
"distance", "population", "price", "cost", "number", "many", "much", "there"}
BROWSER = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 "
"Safari/537.36", "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"}
WIKI_UA = {"User-Agent": "LumiRobot/1.0 (https://cutshion.com; cutshion@cutshion.com)"} # Wikimedia answers 429
# (too many requests) to a browser or bare robot name; a name with a contact it serves
SEARCH_WAIT_S = 3.0 # s all sources get together; a slower one is left out (Naver ~0.5 s, Wikipedia ~1.5 s)
PAGE_CHARS = 1800 # chars of the search page given to the LLM (it reads ~1000 tokens a second)
BLOCK_CHARS = 700 # ... at most this much from one part of the page (an answer box, the news, one site)
WIKI_CHARS = 600 # chars of the Wikipedia summary
SEARCH_TTL = 600 # s a search result is reused (visitors ask the same things; follow-ups search again)
SKIP_BLOCKS = re.compile(r'ad_section|data-meta-ssuid="(influencer|clip|image|qra|shortents|ex_csa|shopping)"|'
r"가격비교|플러스 스토어|브라우저를 업데이트하세요") # Naver page parts that never answer a question
JUNK = re.compile(r"새 창 열림|새 창으로 열기|Keep에 (저장|바로가기)|Keep 바로가기|문서 저장하기|AI 출처 정보.*?자세히 보기|"
r"이 (광고|정보)가 표시된 이유|정보확인 레이어 닫기|레이어 닫기|이전으로 이동|다음으로 이동|이전 다음|"
r"동영상 바로재생( 버튼)?|펼치기|접기|공유하기|차트를 불러오는 중입니다\.|"
r"환율을 (계산할|변환하는) 국가를 선택( [가-힣]+)+|환율우대 \d+%|환율우대없음")
ASKED_AS = ((r"\bhow (tall|high)\b", "height"), (r"\bhow long\b", "length"), (r"\bhow old\b", "age"),
(r"\bhow far\b", "distance"), (r"\bhow deep\b", "depth"), (r"\bhow (big|large)\b", "size"),
(r"\bhow many people\b", "population"), (r"\bhow much\b", "price"), (r"\bwhat time\b", "hours"),
(r"\bwho won\b", "winner"), (r"\bwhere is\b", "location")) # English question -> what a search engine wants
ASK_WORDS = re.compile(r"\b(what'?s|what|who'?s|who|whom|which|where|when|why|how|is|are|was|were|the|a|an|do|does|did|"
r"can|could|you|tell me|please|lumi|right now|i|me|my|and|he|she|his|her|it|its|they|their)\b|"
r"[?,.!]", re.I)
CURRENCIES = {"USD": ("US dollar", r"dollars?|usd|달러"), "EUR": ("euro", r"euros?|eur\b|유로"),
"JPY": ("Japanese yen", r"\byen\b|jpy|엔화"), "CNY": ("Chinese yuan", r"yuan|renminbi|cny|위안"),
"GBP": ("British pound", r"pounds? sterling|british pounds?|gbp|파운드"),
"VND": ("Vietnamese dong", r"vietnamese dong|vnd|동화"), "THB": ("Thai baht", r"baht|thb|바트"),
"KRW": ("Korean won", r"\bwons?\b|krw|원화")}
COINS = {"bitcoin": r"bitcoin|btc|비트코인", "ethereum": r"ethereum|\beth\b|이더리움", "ripple": r"\bxrp\b|ripple|리플",
"solana": r"solana|솔라나", "dogecoin": r"doge|도지"}
RATE_WORDS = re.compile(r"exchange|\brates?\b|convert|환율|환전|in (korean )?wons?\b|원으로|얼마", re.I)
_searched = {} # query -> (time, text)
_pool = ThreadPoolExecutor(6)
def _text(page):
"""Visible text of an HTML fragment on one line."""
page = re.sub(r"(?is)<(script|style|noscript|svg)[^>]*>.*?</\1>", " ", page)
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", page))).strip()
def keywords(query):
"""An English question as search words: "How tall is Son Heung-min?" -> "height Son Heung-min". Naver finds
English blogs about grammar for a whole English question, the right pages for the words. Korean stays as it is."""
if re.search(r"[가-힣]", query):
return query
q = query
for asked, word in ASKED_AS:
q = re.sub(asked, f" {word} ", q, flags=re.I)
return re.sub(r"\s+", " ", ASK_WORDS.sub(" ", q)).strip() or query
def _naver(query):
"""The Naver results page as text: answer boxes (exchange rates, stocks, people, sports), web pages, news, blogs;
ads, shopping and image strips left out. '' when nothing is found. Naver answers scripts like a browser and
has live answer boxes; it reads English questions too."""
page = _get("https://search.naver.com/search.naver?query=" + urllib.parse.quote(query), 4, BROWSER)
parts = []
for block in re.split(r'(?=<div class="_scrollLog")', page)[1:]:
if SKIP_BLOCKS.search(block[:3000]):
continue
text = re.sub(r"\s+", " ", JUNK.sub(" ", _text(block))).strip()
if len(text) > 20:
parts.append(text[:BLOCK_CHARS])
return "\n".join(parts)[:PAGE_CHARS]
def _duckduckgo(query):
"""Titles and snippets from DuckDuckGo, or ''; only when Naver fails (DuckDuckGo often asks scripts to solve a
picture puzzle)."""
page = _get("https://html.duckduckgo.com/html/?q=" + urllib.parse.quote(query), 4, BROWSER)
hits = re.findall(r'class="result__a"[^>]*>(.*?)</a>.*?class="result__snippet"[^>]*>(.*?)</a>', page, re.S)
return "\n".join(f"{_text(t)}: {_text(s)}" for t, s in hits[:6])[:PAGE_CHARS]
def _wikipedia(query, lang):
"""Intro of the Wikipedia article that fits the query best (one request), or ''."""
words = [w for w in re.findall(r"\w+", query.lower()) if w not in STOP]
for q in (" ".join(words), query): # the names alone first: "height in metres" misleads search
if not q:
continue
found = json.loads(_get(f"https://{lang}.wikipedia.org/w/api.php?action=query&format=json&generator=search"
f"&gsrlimit=3&prop=extracts&exintro=1&explaintext=1&exlimit=3&redirects=1"
f"&exchars={WIKI_CHARS}&gsrsearch=" + urllib.parse.quote(q), 3, WIKI_UA)) # full-text search
pages = sorted(found.get("query", {}).get("pages", {}).values(), key=lambda p: p.get("index", 9))
if pages:
break
else:
return ""
best = max(pages, key=lambda p: len(set(words) & set(re.findall(r"\w+", p["title"].lower())))) # title that fits
return f"{best['title']}: {best.get('extract', '')}"
def _news(query, lang, n=4):
"""Latest headlines from Google News for the query, or ''."""
hl = "ko" if lang == "ko" else "en-US"
gl = "KR" if lang == "ko" else "US"
rss = _get(f"https://news.google.com/rss/search?hl={hl}&gl={gl}&ceid={gl}:{hl.split('-')[0]}&q="
+ urllib.parse.quote(query), 3)
items = re.findall(r"<item>.*?<title>(.*?)</title>.*?<pubDate>(.*?)</pubDate>", rss, re.S)[:n]
return "\n".join(f"- {html.unescape(t)} ({d[:16]})" for t, d in items)
def _money(query):
"""Exchange rates to the Korean won (open.er-api.com, updated daily) and coin prices (CoinGecko, live) for the
currencies and coins the query names, or ''. Naver shows its rate box only for some wordings."""
lines = []
named = [c for c, (_, words) in CURRENCIES.items() if re.search(words, query, re.I)]
if named and RATE_WORDS.search(query):
r = json.loads(_get("https://open.er-api.com/v6/latest/USD", 3))
rates = r["rates"]
for c in [c for c in named if c != "KRW"] or ["USD"]:
won = rates["KRW"] / rates[c]
lines.append(f"1 {CURRENCIES[c][0]} = {won:,.2f} Korean won" + (f" (100 yen = {won * 100:,.0f} won)" if
c == "JPY" else "") + (f" = {1 / rates[c]:,.4f} US dollars" if c != "USD" else ""))
lines.append(f"(exchange rates of {r['time_last_update_utc'][:16]})")
coins = [c for c, words in COINS.items() if re.search(words, query, re.I)]
if coins:
price = json.loads(_get("https://api.coingecko.com/api/v3/simple/price?vs_currencies=usd,krw&ids="
+ ",".join(coins), 3))
lines += [f"1 {c} = {p['usd']:,} US dollars = {p['krw']:,} Korean won (now)" for c, p in price.items()]
return "\n".join(lines)
BIRTH = (re.compile(r"\bborn(?: on)? ([A-Z][a-z]+ \d{1,2}, \d{4}|\d{1,2} [A-Z][a-z]+ \d{4})"),
re.compile(r"(?:출생|생년월일) ?:? ?(\d{4})\. ?(\d{1,2})\. ?(\d{1,2})"),
re.compile(r"(\d{4})년 (\d{1,2})월 (\d{1,2})일 ?(?:~|생|출생)"))
BIRTH_YEAR = re.compile(r"\bborn (?:in )?(\d{4})\b|(\d{4})년생") # the year only: the age is one of two
def _born(m):
"""The date a BIRTH match names, or None."""
if len(m.groups()) == 3:
return datetime.date(*map(int, m.groups()))
for form in ("%B %d, %Y", "%d %B %Y"):
try:
return datetime.datetime.strptime(m.group(1), form).date()
except ValueError:
pass
return None
def with_ages(text, today=None):
"""Each birth date in the text followed by the age it makes today ("born May 7, 1996 (30 years old today)"):
the LLM gets ages a year wrong."""
today = today or datetime.date.today()
def age(m):
try:
born = _born(m)
except ValueError: # "1992.13.40"
born = None
if not born:
return m.group(0)
years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
return f"{m.group(0)} ({years} years old today)"
for pattern in BIRTH:
text = pattern.sub(age, text)
def either(m):
years = today.year - int(m.group(1) or m.group(2))
return f"{m.group(0)} ({years - 1} or {years} years old today)"
return BIRTH_YEAR.sub(either, text)
def search(query, n=4):
"""Text to answer a question from, fetched at the same time: exchange rates and coin prices when asked, the
Naver results page (DuckDuckGo when Naver fails), a Wikipedia summary and Google News headlines. "No results." when nothing is found,
None without internet. (Bing returns unrelated pages to scripts.)"""
lang = "ko" if re.search(r"[가-힣]", query) else "en"
q = re.sub(r"\b(what|who|whom|is|are|was|were|the|a|an|about|tell me|more|please|latest|news|today'?s?|any|how|"
r"do|does|did|you|know|can|could|of|lumi)\b|[?,.!]", " ", query, flags=re.I)
q = re.sub(r"\s+", " ", q).strip() or query
key = query.strip().lower()
if key in _searched and time.time() - _searched[key][0] < SEARCH_TTL:
return _searched[key][1]
jobs = {"Rates and prices": _pool.submit(_money, query)} if RATE_WORDS.search(query) or \
any(re.search(w, query, re.I) for w in COINS.values()) else {}
jobs |= {"Search results": _pool.submit(_naver, keywords(query)), "Wikipedia": _pool.submit(_wikipedia, q, lang)}
jobs["News headlines"] = _pool.submit(_news, q, lang, n) # names who holds an office or won lately
wait(jobs.values(), timeout=SEARCH_WAIT_S)
found = {}
for name, job in jobs.items():
try:
found[name] = job.result(timeout=0) if job.done() else ""
except Exception:
found[name] = ""
if not found["Search results"]:
try:
found["Search results"] = _duckduckgo(keywords(query))
except Exception:
pass
text = with_ages("\n\n".join(f"{name}:\n{t}" for name, t in found.items() if t))
if not text:
return None if not online() else "No results."
_searched[key] = (time.time(), text)
return text
OPENAI_KEY = Path.home() / ".config" / "lumi" / "openai_key" # the owner's key, on this Thor only (never copied)
OPENAI_MODEL = "gpt-5.4-mini" # with web_search: right on live facts, 2-6 s (2026-10-21); ~1.5 cents a question
OPENAI_WAIT_S = 12.0 # s; slower than this: the free search below answers instead
OPENAI_HISTORY = 4 # earlier turns given along, for "and his age?"
OPENAI_SAY = ("You are Lumi, a friendly service robot speaking aloud. Answer the question from a web search in 1-2 short "
"spoken sentences, in the question's language (English or Korean), the answer first. On 'tell me more' "
"give 2-3 new facts. Round long numbers; say heights, ages and scores exactly. Now it is {today} in Seoul, Korea (where Lumi is). Never "
"give a private person's address or phone number. No links, sources, lists or markdown.")
CITATION = re.compile(r"\s*\(\[[^\]]*\]\([^)]*\)\)|\[([^\]]*)\]\([^)]*\)|https?://\S+|[*#`]")
def openai_ready():
return OPENAI_KEY.exists()
def openai_answer(question, history=()):
"""A short spoken answer to a web question from OpenAI's web search, or None (no key, no internet, too slow).
history: earlier (heard, said) pairs of the conversation."""
if not openai_ready():
return None
turns = [{"role": r, "content": c} for h, a in list(history)[-OPENAI_HISTORY:] for r, c in (("user", h), ("assistant", a))
if c and not c.startswith("ACTION:")]
body = {"model": OPENAI_MODEL, "reasoning": {"effort": "low"}, "tools": [{"type": "web_search"}],
"instructions": OPENAI_SAY.format(today=datetime.datetime.now().strftime("%A %Y-%m-%d %H:%M")),
"input": turns + [{"role": "user", "content": question}]}
req = urllib.request.Request("https://api.openai.com/v1/responses", json.dumps(body).encode(),
{"Authorization": f"Bearer {OPENAI_KEY.read_text().strip()}",
"Content-Type": "application/json"})
try:
with _opener().open(req, timeout=OPENAI_WAIT_S) as r:
out = json.loads(r.read())
except (OSError, ValueError) as e:
print(f"openai: {e}", file=sys.stderr)
return None
text = " ".join(c.get("text", "") for o in out.get("output", []) if o.get("type") == "message"
for c in o.get("content", []))
text = re.sub(r"\s+", " ", CITATION.sub(lambda m: m.group(1) or "", text)).strip()
return text or None
if __name__ == "__main__":
if len(sys.argv) > 2 and sys.argv[1] == "weather":
print(weather(" ".join(sys.argv[2:])))
elif len(sys.argv) > 2 and sys.argv[1] == "search":
print(search(" ".join(sys.argv[2:])))
else:
print(now_text(), "| internet:", online())
+179
View File
@@ -0,0 +1,179 @@
"""Marker names and numbers as people say them (English, Korean, mixed, and as whisper writes them) -> the written
form the readers use. brain (keyword rules, fetch, named_place) and steps (missions, the LLM check) both read
through norm(), so a place or a number is read the same way everywhere.
"피쓰리로 가 줘", "피 삼으로", "포인트 쓰리", "삼 번 포인트", "point three", "P.3", "피3" -> "p3"
"파이널로" -> "final로" "도크 투", "dock two" -> "dock2" "엑시트" -> "exit" "홈으로" -> "home으로"
"일 미터 반", "1미터 50센치", "one and a half meters" -> "1.5 m" "오십 센치", "half a meter" -> "0.5 m"
Only clear forms are changed: "피로 가" (no number), "PE로", "피자", "이번에" stay as they are, and Lumi asks.
python assistant/wording.py "피쓰리로 가서 일 미터 앞으로 가"
"""
import re
import sys
EN_NUM = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
"ten": 10, "eleven": 11, "twelve": 12}
KO_EN_NUM = {"원": 1, "투": 2, "쓰리": 3, "스리": 3, "뜨리": 3, "트리": 3, "포": 4, "파이브": 5, "화이브": 5,
"식스": 6, "씩스": 6, "세븐": 7, "쎄븐": 7, "에잇": 8, "에이트": 8, "나인": 9, "텐": 10, "일레븐": 11,
"트웰브": 12} # English numbers said in Korean ("피쓰리", "포인트 원")
NATIVE = {"한": 1, "두": 2, "세": 3, "네": 4, "다섯": 5, "여섯": 6, "일곱": 7, "여덟": 8, "아홉": 9, "열": 10}
SINO = {"일": 1, "이": 2, "삼": 3, "사": 4, "오": 5, "육": 6, "륙": 6, "칠": 7, "팔": 8, "구": 9}
_D = "[일이삼사오육륙칠팔구]"
_SINO = rf"(?:{_D}?천(?:{_D}?백)?(?:{_D}?십)?{_D}?|(?:{_D}?백)(?:{_D}?십)?{_D}?|{_D}?십{_D}?|{_D})" # 일 … 구천구백구십구
TENS = {"twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90}
NUM_WORDS = {"one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8",
"nine": "9", "ten": "10", "a": "1", "an": "1", "한": "1", "두": "2", "세": "3", "네": "4"}
UNIT = (r"(?:m|meters?|metres?|metals?|cm|centimet(?:er|re)s?|mm|millimet(?:er|re)s?|km|kilomet(?:er|re)s?|miles?|"
r"미터|센티(?:미터)?|센치(?:미터)?|밀리(?:미터)?|킬로(?:미터)?(?!그램)|마일)") # whisper writes "metal" for meter
_CM = r"(?:cm|centimet(?:er|re)s?|센티(?:미터)?|센치(?:미터)?)"
# what may follow a number said in Korean words for it to be a marker: a particle, a place word, or no more Hangul
# ("피삼으로", "피파이브 앞에", "피일에서"; not "피투성이", "피오나")
_KO_END = (r"(?=(?:(?:으로|로|에서|에게|에다|에|까지|부터|중에서|중에|중|또는|번|이|가|은|는|도|랑|이랑|하고|의|한테)(?![가-힣])"
r"|(?:으로|로|에)(?=가|와|돌아|이동|갔)|(?:이나|나)(?=\s|$)|(?:앞|뒤|옆|위|쪽|근처))|(?![가-힣]))")
_P = r"(?:(?<![가-힣])피|\bp|포인트|마커|\bpoint|\bmarker)" # what is said before a marker's number
NAMED = [ # other markers on the map, as said / as whisper writes them -> the name
(r"(?:파이[널날]|화이[널날])(?:\s*포인트)?|파이너(?=로|에)", "final"),
(r"\bdo(?:ck|c|k)\s*-?\s*(?:2|two)(?![a-z0-9])|\bdock(?:y|u|ie)\s?2\b|(?:도크|독|닥)\s*(?:2|투|트)" + _KO_END, "dock2"),
(r"(?:엑시트|엑싯|엑짓|엑지트|에그짓|이그짓)", "exit"),
(r"(?<![가-힣])피트(?=으로|로|에서|까지|\s*앞)", "p2"), # whisper writes 피투 as 피트 ("피트로 가서")
(r"\b(?:p\.?\s?o\.?|pio)(?=\s*(?:으로|로|에서|에|까지))", "p5"), # 피오 as letters ("PO에서", "P.O.로")
(r"\bp[\s.-]?init(?![a-z])|피\s?이?닛|피\s?이?니트", "pinit"),
(r"\bw[\s.-]p\b|더블[유류]\s?피" + _KO_END, "wp"),
(r"(?<![가-힣])홈" + _KO_END, "home"),
(r"(?:포인트|마커)\s*(?:에이|a)(?![a-z])" + _KO_END, "point a"), (r"(?:포인트|마커)\s*(?:비|b)(?![a-z])" + _KO_END, "point b"),
(r"(?<![가-힣])(?:에이|a)\s*지점", "point a"), (r"(?<![가-힣])(?:비|b)\s*지점", "point b"), # "에이 지점으로 가"
]
def sino(word):
"""'사십오' -> 45, '백팔십' -> 180, '십' -> 10."""
n, part = 0, 0
for ch in word:
if ch in SINO:
part = SINO[ch]
else:
n += (part or 1) * {"십": 10, "백": 100, "천": 1000}[ch]
part = 0
return n + part
def _num(word):
return EN_NUM.get(word) or KO_EN_NUM.get(word) or (int(word) if word.isdigit() else sino(word))
def markers(t):
"""Marker names in lower-case text -> "p3", "final", "dock2", "exit", "pinit", "wp", "home", "point a"."""
ko = "|".join(sorted(KO_EN_NUM, key=len, reverse=True))
t = re.sub(rf"(?<![\w.])({_SINO}|\d+|{'|'.join(NATIVE)})\s*번\s*(?:포인트|마커|point|marker)", # "3번 포인트",
lambda m: f"p{NATIVE.get(m.group(1)) or _num(m.group(1))}", t) # "삼 번", "세 번 포인트"
t = re.sub(rf"(?:포인트|마커|point|marker)\s*({_SINO}|\d+)\s*번", lambda m: f"p{_num(m.group(1))}", t)
t = re.sub(rf"(?<![가-힣])({_SINO})\s*번(?=\s*(?:으로|로|에서|에|까지))", # "삼 번으로" -> "3번으로"
lambda m: m.group(0) if m.group(0) == "이번" and t[m.end():m.end() + 1] == "에" # "이번에": this time
else f"{sino(m.group(1))}번", t)
for name_re, name in NAMED:
t = re.sub(name_re, name, t)
t = re.sub(rf"{_P}\s*[.-]?\s*(\d+)(?!\d|\.\d)", lambda m: f"p{m.group(1)}", t) # "P.3", "p 3", "피3", "포인트 3"
t = re.sub(r"(?<![\w.])(\d+)\s?(?:p(?:\s+(?:point|포인트))?|point|포인트)(?![a-z\d])(?!\s*\d)", # "10p point",
lambda m: f"p{m.group(1)}", t) # "10p", "10 point"
t = re.sub(rf"(?<!\d )(?<![a-z] point ){_P}\s*[.-]?\s*({'|'.join(EN_NUM)})(?![a-z])(?!\s*{UNIT}\b)",
lambda m: f"p{EN_NUM[m.group(1)]}", t) # "point three", "p two"
t = re.sub(rf"{_P}\s*({ko}|{_SINO}){_KO_END}", lambda m: f"p{_num(m.group(1))}", t) # "피쓰리", "포인트 삼"
t = re.sub(r"\b(to|from|at) (the )?(?:piece|peace|pee|pea|pit|pi|pe) ?(\d+)\b", # whisper's "go to piece 6"
lambda m: f"{m.group(1)} {m.group(2) or ''}p{m.group(3)}", t)
t = re.sub(r"\b(p\d+)\s+(?:point|포인트)(?![a-z])(?!\s*(?:a|b|\d)(?![a-z]))", r"\1", t) # "p10 point"
return t
def numbers(t):
"""Distances and angles in lower-case text -> digits and metres: "half a meter" -> "0.5 m", "오십 센치" -> "0.5 m",
"일 미터 반" -> "1.5 m", "구십 도" -> "90도"."""
t = re.sub(r"\bone and a half\b", "1.5", t)
t = re.sub(rf"\b({'|'.join(TENS)})(?:[ -]({'|'.join(list(EN_NUM)[:9])}))?\b",
lambda m: str(TENS[m.group(1)] + EN_NUM.get(m.group(2), 0)), t)
t = re.sub(rf"\b(?:a|one|1) thousand\b|\b(\d+|{'|'.join(EN_NUM)}) thousand\b",
lambda m: str(1000 * _num(m.group(1)) if m.group(1) else 1000), t) # "a thousand", "five thousand"
t = re.sub(rf"\b([2-9]|{'|'.join(list(EN_NUM)[1:9])}) hundred(?: and)?(?: (\d+))?\b",
lambda m: str(100 * _num(m.group(1)) + int(m.group(2) or 0)), t) # "two hundred and fifty"
t = re.sub(rf"\b({'|'.join(TEEN)}|eleven|twelve)\b(?=\s*{UNIT}(?![a-z]))",
lambda m: str(TEEN.get(m.group(1)) or EN_NUM[m.group(1)]), t) # "fifteen centimetres"
t = re.sub(r"\b(?:a|one) hundred(?: and)? (\d+)\b", lambda m: str(100 + int(m.group(1))), t)
t = re.sub(r"\b(?:a|one) hundred\b", "100", t)
t = re.sub(rf"(?<![\w.])(\d|{'|'.join(list(EN_NUM)[:9])}) point (\d|{'|'.join(list(EN_NUM)[:9])})\s*(?={UNIT}\b)",
lambda m: f"{_num(m.group(1))}.{_num(m.group(2))} ", t) # "one point five meters"
t = re.sub(rf"\b(?:zero |oh )?point ({'|'.join(list(EN_NUM)[:9])}|\d)\s*(?={UNIT}\b)",
lambda m: f"0.{_num(m.group(1))} ", t) # "point five meters"
t = re.sub(rf"(?<![가-힣])(?:({_SINO})|[영공])\s*점\s*({_D})\s*(?={UNIT})",
lambda m: f"{sino(m.group(1)) if m.group(1) else 0}.{SINO[m.group(2)]} ", t) # "영점오 미터", "일 점 오"
t = re.sub(rf"(?<![가-힣\d])({_SINO})\s*(?={UNIT}(?![a-z]))", lambda m: f"{sino(m.group(1))} ", t) # "오십 센치"
t = re.sub(rf"(?:(?<=으로)|(?<=로))\s*({_SINO})\s*도(?![가-힣])", lambda m: f" {sino(m.group(1))}도", t)
t = re.sub(rf"(?<![가-힣\d])({_SINO})\s*도(?=\s+(?:왼쪽|오른쪽|뒤로|돌))", lambda m: f"{sino(m.group(1))}도", t)
t = re.sub(r"(\d+)\s*degrees?(?=\s*[가-힣])", r"\1도", t) # "왼쪽으로 45 degrees 돌아"
t = re.sub(rf"\bhalf (?:a |an )?{UNIT}", "0.5 m", t)
t = re.sub(rf"반\s*{UNIT}", "0.5 m", t)
for w, d in NUM_WORDS.items():
if w.isascii():
t = re.sub(rf"\b{w}\b(?=\s*(?:{UNIT}(?![a-z])|degrees?|and a (?:half|0\.5)))", d, t) # "one meter", "a meter"
else:
t = re.sub(rf"(?<![가-힣]){w}\s*(?={UNIT})", d + " ", t)
t = re.sub(rf"(?<![\d.])0(\d)\s*(?={UNIT}(?![a-z]))", r"0.\1 ", t) # whisper's "05 meters": 0.5 m
t = re.sub(rf"(\d+(?:\.\d+)?)\s*{_CM}(?![a-z])", lambda m: f"{float(m.group(1)) / 100:g} m", t)
t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:mm|millimet(?:er|re)s?|밀리(?:미터)?)(?![a-z])",
lambda m: f"{float(m.group(1)) / 1000:g} m", t)
t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:km|kilomet(?:er|re)s?|킬로(?:미터)?(?!그램))(?![a-z])",
lambda m: f"{float(m.group(1)) * 1000:g} m", t)
t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:miles?|마일)(?![a-z])", lambda m: f"{float(m.group(1)) * 1609.344:g} m", t)
t = re.sub(r"(\d+(?:\.\d+)?)\s*(?:meters?|metres?|metals?|미터)", r"\1 m", t)
t = re.sub(r"(?<![\d.])(\d+) m (0\.\d+) m", lambda m: f"{int(m.group(1)) + float(m.group(2)):g} m", t) # "1미터 50센치"
t = re.sub(r"(?<![\d.])(\d+)(?: m)? and (?:a )?(?:half|0\.5)(?: m)?", lambda m: f"{int(m.group(1)) + 0.5:g} m", t)
t = re.sub(r"(?<![\d.])(\d+) ?m 반", lambda m: f"{int(m.group(1)) + 0.5:g} m", t)
t = re.sub(r"\ba 0\.5 m", "0.5 m", t)
return re.sub(r"(\d)\s*m(?![a-z])", r"\1 m", t)
TEEN = {"thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19}
_SEC = r"(?:seconds?|secs?|s)(?![a-z])"
_MIN = r"(?:minutes?|mins?)(?![a-z])"
_HOUR = r"(?:hours?|hrs?)(?![a-z])"
# what may follow a Korean time: not a particle that makes "이 분" / "두 분" people ("이 분한테 줘", "두 분께")
_KO_TIME_END = r"(?!\s*(?:께|한테|에게|들|이랑|하고|의(?![가-힣])|은(?![가-힣])|는(?![가-힣])|이(?![가-힣])|에(?![가-힣])))"
def durations(t):
"""Times in lower-case normalised text -> seconds written "<n> s": "2 minutes" -> "120 s", "half an hour" ->
"1800 s", "1분 30초" -> "90 s", "오 분" -> "300 s", "한 시간" -> "3600 s". Vague ones ("a few minutes", "몇 분")
stay as they are. Used by the mission reader only (brain keeps the words)."""
words = {**EN_NUM, **TEEN, "a": 1, "an": 1}
en = rf"(\d+(?:\.\d+)?|{'|'.join(sorted(words, key=len, reverse=True))})"
val = lambda w: float(w) if w[0].isdigit() else words[w]
t = re.sub(r"\bhalf (?:an|a) hour\b", "1800 s", t)
t = re.sub(r"\b(?:a )?quarter (?:of an )?hour\b", "900 s", t)
t = re.sub(r"\bhalf a minute\b", "30 s", t)
t = re.sub(rf"\b{en} and a half {_MIN}|\b{en} {_MIN} and a half\b",
lambda m: f"{(val(m.group(1) or m.group(2)) + 0.5) * 60:g} s", t)
t = re.sub(rf"\b{en} {_HOUR}", lambda m: f"{val(m.group(1)) * 3600:g} s", t)
t = re.sub(rf"\b{en} ?{_MIN}(?:,? (?:and )?(\d+) ?{_SEC})?",
lambda m: f"{val(m.group(1)) * 60 + float(m.group(2) or 0):g} s", t)
sec = en.replace("|an|a)", ")") # "a second" is a short wait, not 1 s (steps.WAIT_SHORT_S)
t = re.sub(rf"(?<![\w.]){sec} ?{_SEC}", lambda m: f"{val(m.group(1)):g} s", t)
# Korean: 초 / 분 with digits or sino numbers, 시간 with native numbers or digits; "1분 30초", "1분 반"
ko = rf"(\d+(?:\.\d+)?|{_SINO})"
kval = lambda w: float(w) if w[0].isdigit() else sino(w)
t = re.sub(rf"(?<![가-힣\d.])(\d+|{'|'.join(NATIVE)}|{_SINO})\s*시간(?:\s*(반))?{_KO_TIME_END}",
lambda m: f"{((NATIVE.get(m.group(1)) or kval(m.group(1))) + (0.5 if m.group(2) else 0)) * 3600:g} s", t)
t = re.sub(rf"(?<![가-힣\d.]){ko}\s*분(?:\s*(?:{ko}\s*초|(반)))?{_KO_TIME_END}",
lambda m: f"{kval(m.group(1)) * 60 + (kval(m.group(2)) if m.group(2) else 30 if m.group(3) else 0):g} s",
t)
t = re.sub(rf"(?<![가-힣\d.]){ko}\s*초(?![가-힣])|(?<![가-힣\d.]){ko}\s*초(?=동안|정도|만|쯤|간|후|뒤)",
lambda m: f"{kval(m.group(1) or m.group(2)):g} s", t)
return t
def norm(text):
"""Lower case, numbers first ("point five meters" is a distance), then marker names."""
t = " " + (text or "").lower().replace("’", "'") + " "
return re.sub(r"\s+", " ", markers(numbers(t))).strip()
if __name__ == "__main__":
print(norm(" ".join(sys.argv[1:])))
View File
+70
View File
@@ -0,0 +1,70 @@
"""Turn the singer's separated vocal into Lumi's voice (an "AI cover"): words, melody, timing and feeling stay the
singer's, the voice becomes Lumi's. Zero-shot singing voice conversion with Seed-VC (its 44.1 kHz pitch-conditioned
model) and a 25 s reference of Lumi's TTS voice. Offline tool: runs only in the render venv .venv-cover (torch
CUDA), with the Seed-VC code in models/seed-vc (local, GPL-3.0, not part of the robot's software).
.venv-cover/bin/python audio/cover.py MEOMUREU_DREAMED_ADULT
Reads data/songs/mine/<NAME>/vocals.wav (audio/separate.py), writes data/songs/mine/<NAME>/vocal_lumi.wav.
Then audio/sing_mine.py mixes it with the instrumental and picks the part to sing.
"""
import argparse
import os
import pathlib
import sys
import time
ROOT = pathlib.Path(__file__).resolve().parents[1]
SEED_VC = ROOT / "models" / "seed-vc"
MINE = ROOT / "data" / "songs" / "mine"
REFERENCE = MINE / "lumi_voice" / "ref25.wav" # 25 s of Lumi's TTS voice (F1), Korean and English
STEPS = 40 # diffusion steps (Seed-VC suggests 30-50 for singing)
CFG_RATE = 0.7 # how strongly the result follows the reference voice
SEMITONES = 0 # the singer's pitch is kept exactly
FP16 = True # half precision on the GPU
# Seed-VC fine-tuned on Lumi's voice (audio/lumi_voice_set.py, 300 clips / 24 min; train.py, 1000 steps from the
# 44.1 kHz pitch model). Tried on 꿈꾸던 어른이 되었나요: no closer to Lumi than the base model with REFERENCE alone
# (speaker similarity 0.81 against 0.83), so it is used only when asked (--fine-tuned)
FINE_TUNED = SEED_VC / "runs" / "run_dit_mel_seed_uvit_whisper_base_f0_44k" / "lumi_f0_44k"
def convert(name, steps=STEPS, cfg=CFG_RATE, semitones=SEMITONES, reference=REFERENCE, source=None, result=None,
fine_tuned=False):
"""source / result: another vocal file and output (tries on a part); default the whole vocal."""
import soundfile as sf
import torchaudio
folder = MINE / name
source = pathlib.Path(source).resolve() if source else folder / "vocals.wav" # before the chdir below
result = pathlib.Path(result).resolve() if result else folder / "vocal_lumi.wav"
out = folder / "seedvc"
out.mkdir(exist_ok=True)
# this torchaudio saves only through torchcodec; Seed-VC's one save goes through soundfile instead
torchaudio.save = lambda path, wav, sr: sf.write(path, wav.numpy().T, sr)
sys.path.insert(0, str(SEED_VC))
os.chdir(SEED_VC)
import inference
ft = fine_tuned and (FINE_TUNED / "ft_model.pth").exists()
args = argparse.Namespace(source=str(source), target=str(reference), output=str(out),
diffusion_steps=steps, length_adjust=1.0, inference_cfg_rate=cfg, f0_condition=True,
auto_f0_adjust=False, semi_tone_shift=semitones, fp16=FP16,
checkpoint=str(FINE_TUNED / "ft_model.pth") if ft else None,
config=str(next(FINE_TUNED.glob("*.yml"))) if ft else None)
t = time.time()
inference.main(args)
made = max(out.glob("vc_*.wav"), key=os.path.getmtime)
made.rename(result)
print(f"{result} ({time.time() - t:.0f} s)")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("name")
ap.add_argument("--steps", type=int, default=STEPS)
ap.add_argument("--cfg", type=float, default=CFG_RATE)
ap.add_argument("--semitones", type=int, default=SEMITONES)
ap.add_argument("--reference", default=str(REFERENCE))
ap.add_argument("--source")
ap.add_argument("--result")
ap.add_argument("--fine-tuned", action="store_true", help="the model fine-tuned on Lumi's voice")
a = ap.parse_args()
convert(a.name, a.steps, a.cfg, a.semitones, pathlib.Path(a.reference), a.source, a.result, a.fine_tuned)
+115
View File
@@ -0,0 +1,115 @@
"""Judge a converted vocal (Lumi's voice cover) against the singer's original, without listening. Offline tool for
the render venv (.venv-cover: resemblyzer); prints numbers only, never lyrics.
.venv-cover/bin/python audio/cover_check.py data/songs/mine/<NAME>/vocals.wav <converted.wav> [start end]
(a) words: whisper (the running server) on both, cut the same way at the singer's phrases, the similarity of the
two transcripts, and how many characters
each gave; (b) voice: speaker-embedding similarity of the converted vocal to Lumi (data/songs/mine/lumi_voice)
and to the original singer; (c) melody: correlation and median difference of the two pitch contours;
(d) clipping and silent gaps where the singer sings.
"""
import difflib
import json
import pathlib
import re
import subprocess
import sys
import tempfile
import numpy as np
import soundfile as sf
from audio import sing_mine as M
ROOT = pathlib.Path(__file__).resolve().parents[1]
LUMI = ROOT / "data" / "songs" / "mine" / "lumi_voice"
STT_URL = "http://127.0.0.1:8096/inference"
PIECE_S = 25 # s per whisper request
GAP_S = 0.3 # s; a silent stretch this long where the singer sings is a gap
SINGING = 0.5 # the singer sings where the vocal is above this part of its loud level (lower is
# mostly the reverb tail of a phrase, which the converted vocal rightly leaves out)
def load(path, sr=44100):
x, r = sf.read(path, dtype="float32", always_2d=True)
x = x.mean(1)
if r != sr:
x = np.interp(np.arange(int(len(x) * sr / r)) * r / sr, np.arange(len(x)), x).astype(np.float32)
return x
def pieces(x, sr=44100):
"""[(start, end) samples]: the singer's phrases joined into pieces up to PIECE_S, so whisper hears whole lines
(fixed 25 s cuts split words, and whisper drops parts of a long song)."""
out = []
for a, b in M.phrases(x):
if out and b - out[-1][0] / sr <= PIECE_S:
out[-1] = (out[-1][0], int(b * sr))
else:
out.append((int(max(0.0, a - 0.2) * sr), int(b * sr)))
return out
def transcript(x, cuts, sr=44100):
out = []
with tempfile.TemporaryDirectory() as d:
for a, b in cuts:
p = pathlib.Path(d) / "p.wav"
sf.write(p, x[a:b + int(0.3 * sr)], sr)
subprocess.run(["sox", str(p), "-r", "16000", "-c", "1", "-b", "16", str(p.with_name("p16.wav"))],
check=True, stderr=subprocess.DEVNULL)
r = subprocess.run(["curl", "-s", "-F", f"file=@{p.with_name('p16.wav')}", "-F", "response_format=json",
"-F", "language=ko", STT_URL], capture_output=True, text=True).stdout
out.append(json.loads(r).get("text", ""))
return re.sub(r"\W", "", " ".join(out)).lower()
def embed(enc, x, sr=44100):
from resemblyzer import preprocess_wav
return enc.embed_utterance(preprocess_wav(x, source_sr=sr))
def check(orig_path, conv_path, start=None, end=None):
from resemblyzer import VoiceEncoder
sr = 44100
o, c = load(orig_path), load(conv_path)
n = min(len(o), len(c))
o, c = o[:n], c[:n]
if start is not None:
o, c = o[int(start * sr):int(end * sr)], c[int(start * sr):int(end * sr)]
cuts = pieces(o) # the same cuts for both
to, tc = transcript(o, cuts), transcript(c, cuts)
words = difflib.SequenceMatcher(None, to, tc).ratio()
enc = VoiceEncoder("cpu")
lumi = np.mean([embed(enc, load(p)) for p in sorted(LUMI.glob("line_*.wav"))], 0)
e_c, e_o = embed(enc, c), embed(enc, o)
cos = lambda a, b: float(np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b))
f_o, f_c = M.pitch_contour(o), M.pitch_contour(c)
m = min(len(f_o), len(f_c))
both = (f_o[:m] > 0) & (f_c[:m] > 0)
so, sc = 12 * np.log2(f_o[:m][both] / 440), 12 * np.log2(f_c[:m][both] / 440)
diff = sc - so
octave = round(float(np.median(diff)) / 12) * 12 # a whole-octave shift is allowed
e_orig = M.rms(o) > SINGING * np.percentile(M.rms(o), 95)
e_conv = M.rms(c) > 0.02 * np.percentile(M.rms(o), 95)
gap, longest = 0, 0
for so_on, sc_on in zip(e_orig, e_conv):
gap = gap + 1 if so_on and not sc_on else 0
longest = max(longest, gap)
res = {"words_similarity": round(words, 2), "chars_original": len(to), "chars_converted": len(tc),
"voice_sim_to_lumi": round(cos(e_c, lumi), 3), "voice_sim_to_singer": round(cos(e_c, e_o), 3),
"singer_sim_to_lumi": round(cos(e_o, lumi), 3),
"pitch_corr": round(float(np.corrcoef(so, sc)[0, 1]), 3), "pitch_octave_shift": octave,
"pitch_median_err_cents": round(float(np.median(np.abs(diff - octave))) * 100),
"pitch_within_50_cents": round(float((np.abs(diff - octave) < 0.5).mean()), 2),
"pitch_frames_both_voiced": round(float(both.mean()), 2),
"clipped_samples": int((np.abs(c) >= 0.999).sum()), "longest_gap_s": round(longest * 0.01, 2),
"gaps_over_limit": longest * 0.01 >= GAP_S}
print(json.dumps(res, indent=1))
return res
if __name__ == "__main__":
a = sys.argv[1:]
check(a[0], a[1], *(float(x) for x in a[2:4])) if len(a) >= 4 else check(a[0], a[1])
+183
View File
@@ -0,0 +1,183 @@
"""Sound direction (direction of arrival) from the six mics of the head array, SRP-PHAT.
For each candidate direction the expected time differences between the mics of a ring are compared with the
measured cross-spectra (PHAT-weighted); the direction with the most energy wins.
Geometry (to calibrate, kept in doa_calib.json): six mics on a ring of `radius`; mic k sits at
offset + sign * k * 60 deg. Angles are in the head frame: 0 = where the head looks, + = to the robot's left
(same sign as head yaw). Robot (waist) angle = head yaw + this angle.
Calibration needs people at known angles. lumi.py collects them on its own: while it talks with a person
the head camera sees, each utterance of that person is a sample (camera angle = truth). After MIN_SAMPLES
samples spread over at least SPREAD_DEG it fits sign / offset / radius and writes doa_calib.json.
Or by hand:
python audio/doa.py --calibrate # stand in front of the head camera, talk, move left / right, Ctrl+C to fit
"""
import json
import math
import pathlib
import sys
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
CALIB = ROOT / "data" / "doa_calib.json"
SAMPLES = ROOT / "data" / "doa_samples.npz"
RATE = 16000
SOUND = 343.0 # m/s
NFFT, HOP = 512, 256
BAND = (300.0, 3500.0) # Hz used
GRID = np.arange(-180, 180, 2.0) # deg
MIN_SAMPLES, SPREAD_DEG = 6, 30.0
PAIRS = [(i, j) for i in range(6) for j in range(i + 1, 6)]
_freqs = np.fft.rfftfreq(NFFT, 1 / RATE)
_band = (_freqs >= BAND[0]) & (_freqs <= BAND[1])
_f = _freqs[_band]
def load_calib():
try:
c = json.loads(CALIB.read_text())
return {"radius": float(c["radius"]), "offset": float(c["offset"]), "sign": int(c["sign"]), "fitted": True}
except (FileNotFoundError, ValueError, KeyError):
return {"radius": 0.04, "offset": 0.0, "sign": 1, "fitted": False}
def cross_spectra(mics):
"""Average PHAT-normalised cross-spectra of all mic pairs: (15, n_band) complex, or None if too short."""
x = mics.astype(np.float32)
if len(x) < NFFT:
return None
win = np.hanning(NFFT).astype(np.float32)
frames = np.stack([x[i:i + NFFT] * win[:, None] for i in range(0, len(x) - NFFT, HOP)]) # (t, NFFT, 6)
spec = np.fft.rfft(frames, axis=1)[:, _band, :] # (t, F, 6)
energy = (np.abs(spec) ** 2).sum((1, 2))
keep = energy >= np.percentile(energy, 50) # the louder half of the frames: the voice, not pauses
spec = spec[keep]
g = np.stack([(spec[:, :, i] * np.conj(spec[:, :, j])) for i, j in PAIRS]) # (15, t, F)
g = g / (np.abs(g) + 1e-9)
return g.mean(1) # (15, F)
def _steering(radius, offset, sign):
"""(n_grid, 15, F) expected phase for each candidate direction."""
th = np.radians(GRID)[:, None]
phi = np.radians(offset + sign * 60.0 * np.arange(6))[None, :]
tau = -radius * np.cos(th - phi) / SOUND # (n_grid, 6): arrival time of each mic
d = np.stack([tau[:, i] - tau[:, j] for i, j in PAIRS], 1) # (n_grid, 15)
return np.exp(2j * np.pi * _f[None, None, :] * d[:, :, None])
_cache = {}
def _power(g, calib):
key = (calib["radius"], calib["offset"], calib["sign"])
if key not in _cache:
_cache.clear()
_cache[key] = _steering(*key)
return np.real((_cache[key] * g[None]).sum((1, 2))) # (n_grid,)
def estimate(mics, calib=None):
"""(angle deg in the head frame, confidence 0..1, raw angle with the default geometry)."""
calib = calib or load_calib()
g = cross_spectra(mics)
if g is None:
return 0.0, 0.0, 0.0
p = _power(g, calib)
best = int(np.argmax(p))
conf = float((p[best] - np.median(p)) / (np.abs(p).max() + 1e-9))
raw = float(GRID[int(np.argmax(_power(g, {"radius": 0.04, "offset": 0.0, "sign": 1})))])
return float(GRID[best]), max(0.0, min(1.0, conf)), raw
# ---------- calibration ----------
def add_sample(mics, true_deg):
"""Store one utterance with its true head-frame angle; refit when there are enough. Returns the new calib or None."""
g = cross_spectra(mics)
if g is None:
return None
try:
d = np.load(SAMPLES)
gs, ts = list(d["g"]), list(d["t"])
except (FileNotFoundError, KeyError, ValueError):
gs, ts = [], []
gs.append(g)
ts.append(float(true_deg))
gs, ts = gs[-60:], ts[-60:]
np.savez(SAMPLES, g=np.array(gs), t=np.array(ts))
if len(ts) >= MIN_SAMPLES and max(ts) - min(ts) >= SPREAD_DEG:
return fit(np.array(gs), np.array(ts))
return None
def fit(gs, ts):
"""Grid search sign / offset / radius that best explains the samples; saves doa_calib.json."""
best = None
for sign in (1, -1):
for radius in (0.03, 0.035, 0.04, 0.045, 0.05):
for offset in np.arange(0, 360, 5.0):
c = {"radius": radius, "offset": float(offset), "sign": sign}
err = []
for g, t in zip(gs, ts):
a = GRID[int(np.argmax(_power(g, c)))]
err.append(abs((a - t + 180) % 360 - 180))
score = float(np.median(err))
if best is None or score < best[0]:
best = (score, c)
score, c = best
c["median_error_deg"] = round(score, 1)
c["samples"] = len(ts)
c["time"] = time.strftime("%Y-%m-%d %H:%M")
CALIB.write_text(json.dumps(c, indent=1))
_cache.clear()
return c
def calibrate_by_hand():
"""Talk in front of the head camera from several places; the camera gives the true angle."""
from audio import mic
import threading
from vision.camview import RemoteDetector
det = RemoteDetector("head")
seen = {"angle": None, "time": 0.0}
def watch():
while True:
_, people = det.read()
near = [p for p in people if p["distance_m"] and p["distance_m"] < 3.0]
if len(near) == 1: # exactly one person: no doubt who talks
seen.update(angle=near[0]["angle_deg"] - det.head_yaw * det.head_sign, time=time.time())
threading.Thread(target=watch, daemon=True).start()
m = mic.get()
print("Stand 1-2 m in front of the robot, alone in the head camera's view, and talk for a few seconds.\n"
"Then move ~1 m to the left, talk; to the right, talk. Ctrl+C when done.")
n = 0
try:
while True:
u = m.next(1.0)
if u is None or u.seconds < 0.8:
continue
if time.time() - seen["time"] > 1.0:
print(" (heard speech but no single person in view - skipped)")
continue
n += 1
c = add_sample(u.mics, seen["angle"])
print(f" sample {n}: person at {seen['angle']:+.0f} deg, raw estimate {estimate(u.mics)[2]:+.0f} deg"
+ (f" -> calibrated: {c}" if c else ""))
except KeyboardInterrupt:
d = np.load(SAMPLES)
if len(d["t"]) >= 3:
print("fit:", fit(d["g"], d["t"]))
if __name__ == "__main__":
if "--calibrate" in sys.argv:
calibrate_by_hand()
else:
print(load_calib())
+185
View File
@@ -0,0 +1,185 @@
"""Listening: one utterance from the head microphone array (via mic.py) turned into text.
python audio/ears.py # listen once, print what was said (English or Korean)
Recording, speech detection and "do not listen while Lumi talks" are in mic.py (one always-on recording that
lumi.py also uses for the wake word). Speech-to-text: whisper.cpp (GPU) server with large-v3-turbo on
127.0.0.1:8096, started when needed.
"""
import io
import json
import re
import pathlib
import subprocess
import time
import urllib.request
import uuid
import wave
from audio import mic
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
RATE = mic.RATE
STT_URL = "http://127.0.0.1:8096"
WHISPER_SERVER = ROOT / "whisper.cpp/build/bin/whisper-server"
WHISPER_MODEL = ROOT / "models/ggml-large-v3-turbo-q5_0.bin"
PROMPT = "Hi Lumi. Hey Lumi. 루미야." # helps whisper spell the robot's name
last = {} # levels of the last listen() call, for the log: noise, threshold, peak
def ensure_stt_server():
try:
urllib.request.urlopen(f"{STT_URL}/", timeout=1)
return
except OSError:
pass
log = open(ROOT / "logs" / "whisper_server.log", "a")
subprocess.Popen([str(WHISPER_SERVER), "-m", str(WHISPER_MODEL), "--host", "127.0.0.1", "--port", "8096",
"-l", "auto", "-nt"], stdout=log, stderr=log, start_new_session=True)
for _ in range(120):
time.sleep(0.5)
try:
urllib.request.urlopen(f"{STT_URL}/", timeout=1)
return
except OSError:
pass
raise RuntimeError("whisper-server did not start, see whisper_server.log")
def record(wait_s=8.0, on_start=None, abort=None):
"""Wait up to wait_s for speech to start, then until it ends. Returns a mic.Utterance or None.
abort: optional function checked every 30 ms; when it returns True, stop and return None."""
m = mic.get()
m.clear() # only speech that starts from now on
t0, started = time.time(), False
try:
while True:
if abort and abort():
return None
u = m.next(0.03)
if u is not None and u.t_end > t0:
return u
if m.in_speech and not started:
started = True
if on_start:
on_start()
if not m.in_speech and not started and time.time() - t0 > wait_s:
return None
finally:
last.update(noise=round(m.noise), threshold=round(m.threshold))
def louder(audio, target=0.7):
"""Quiet speech from far away: raise the peak to `target` of full scale (at most 12x) for speech-to-text."""
import numpy as np
peak = float(np.abs(audio).max()) if len(audio) else 0.0
if peak < 1:
return audio
gain = min(12.0, target * 32767 / peak)
return np.clip(audio.astype(np.float32) * gain, -32767, 32767).astype(np.int16) if gain > 1.05 else audio
LANGS = {"english": "en", "korean": "ko"}
MIN_LOGPROB = -1.0 # below this average token log-probability whisper was guessing
last_stt = {} # language / confidence of the last transcription (see understood())
HEARD_DIR = ROOT / "logs" / "heard" # the last HEARD_KEEP utterances as wav, to check what Lumi really heard
HEARD_KEEP = 50
def _infer(wav, prompt, language=None):
"""One whisper-server call: (text, language, language probability, average token log-probability)."""
boundary = uuid.uuid4().hex
fields = {"response_format": "verbose_json", "prompt": prompt, **({"language": language} if language else {})}
body = "".join(f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n"
for k, v in fields.items()).encode()
body += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.wav\"\r\n"
f"Content-Type: audio/wav\r\n\r\n").encode() + wav + f"\r\n--{boundary}--\r\n".encode()
req = urllib.request.Request(f"{STT_URL}/inference", body,
{"Content-Type": f"multipart/form-data; boundary={boundary}"})
with urllib.request.urlopen(req, timeout=30) as r:
out = json.loads(r.read())
segs = out.get("segments") or []
logprob = sum(s.get("avg_logprob", 0.0) for s in segs) / len(segs) if segs else 0.0
lang = out.get("language") or out.get("detected_language")
return out.get("text", "").strip(), lang, out.get("detected_language_probability"), logprob
def transcribe(audio, prompt=PROMPT):
"""int16 mono 16 kHz -> text (empty string if nothing understood). Also fills last_stt.
Whisper sometimes names another language (Japanese) for Korean said from afar and writes only the prompt's
"Lumi." (2026-10-20: "컵 좀 주세요" came back as "Lumi." [japanese] four times): then it is asked again with
Korean and with English fixed, and the surer of the two is kept."""
ensure_stt_server()
audio = louder(audio)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(RATE)
w.writeframes(audio.tobytes())
wav = buf.getvalue()
try:
HEARD_DIR.mkdir(parents=True, exist_ok=True)
(HEARD_DIR / time.strftime("%H%M%S.wav")).write_bytes(wav)
for old in sorted(HEARD_DIR.glob("*.wav"), key=lambda p: p.stat().st_mtime)[:-HEARD_KEEP]: # by time: names wrap at midnight
old.unlink()
except OSError:
pass
text, lang, prob, logprob = _infer(wav, prompt)
only_name = re.fullmatch(r"\W*(lumi|루미야?)\W*", text, re.I) and len(audio) > 1.5 * RATE
if lang not in LANGS or only_name:
tries = [(text, lang, prob, logprob)] if lang in LANGS and not only_name else []
for code, name in (("ko", "korean"), ("en", "english")):
t2, _, _, lp2 = _infer(wav, prompt, code)
tries.append((t2, name, None, lp2))
text, lang, prob, logprob = max(tries, key=lambda r: r[3])
last_stt.clear()
last_stt.update(text=text, language=lang, lang_prob=prob, logprob=round(logprob, 2))
# whisper writes things like "[BLANK_AUDIO]" or "(music)" for non-speech
return "" if text.startswith(("[", "(", "*")) else text
def understood(min_logprob=MIN_LOGPROB):
"""Was the last transcription clear English or Korean? (else Lumi asks the visitor to say it again)
The text must also be written in that language: Whisper turns noise or Lumi's own Korean voice into
English sentences tagged 'korean' ("I'll see you next time.", 2026-10-13)."""
lang, text = last_stt.get("language"), last_stt.get("text", "")
if lang not in LANGS or last_stt.get("logprob", 0.0) < min_logprob:
return False
return bool(re.search(r"[가-힣]", text)) == (lang == "korean")
def heard_clearly(min_logprob=MIN_LOGPROB):
"""English or Korean said clearly, whatever script whisper wrote it in ("Can you sing song?" came tagged
'korean', 2026-10-21): lumi.py takes it only for its own fixed commands."""
return last_stt.get("language") in LANGS and last_stt.get("logprob", 0.0) >= min_logprob
def heard_lang(default="en"):
"""'en' or 'ko': the language of the last transcription."""
return LANGS.get(last_stt.get("language"), default)
def listen(wait_s=8.0, on_start=None, abort=None, full=False):
"""Record one utterance and transcribe it. Returns text or None (nobody spoke, or aborted).
full=True: returns (text, mic.Utterance) instead, for the sound direction."""
u = record(wait_s, on_start, abort)
if u is not None:
last["peak"] = round(u.peak)
if u is None or u.seconds < 0.4:
return (None, u) if full else None
text = transcribe(u.mono) or None
return (text, u) if full else text
if __name__ == "__main__":
ensure_stt_server()
print("Say something (English or Korean)...")
u = record(10, on_start=lambda: print(" (hearing you)"))
if u is None:
print("nothing heard")
else:
t = time.time()
print(f"you said: {transcribe(u.mono)!r} ({u.seconds:.1f} s audio, STT {time.time() - t:.2f} s)")
+39
View File
@@ -0,0 +1,39 @@
"""Make a training set of Lumi's voice (Supertonic-3, the voice audio/mouth.py speaks with) for the voice-conversion
model of audio/cover.py: Lumi's own example answers (assistant/talk_examples.py), Korean and English, at varied
speeds. Local only (data/songs/mine/lumi_voice/train/).
.venv/bin/python audio/lumi_voice_set.py [count]
"""
import pathlib
import random
import sys
import numpy as np
import soundfile as sf
from assistant import talk_examples
from audio import mouth
OUT = pathlib.Path(__file__).resolve().parents[1] / "data" / "songs" / "mine" / "lumi_voice" / "train"
COUNT = 300 # clips, about 15 minutes
SPEEDS = (0.8, 1.05) # TTS speed range: slower clips give long vowels
def make(count=COUNT):
OUT.mkdir(parents=True, exist_ok=True)
tts = mouth._load()
rng = random.Random(7)
replies = sorted({r for _, _, _, r in talk_examples.EXAMPLES if 10 <= len(r) <= 160})
rng.shuffle(replies)
total = 0.0
for i, text in enumerate(replies[:count]):
wav, _ = tts.synthesize(text, voice_style=mouth._style, lang=mouth.lang_of(text), total_steps=8,
speed=rng.uniform(*SPEEDS))
wav = np.asarray(wav, np.float32).reshape(-1)
sf.write(OUT / f"{i:04d}.wav", wav, tts.sample_rate)
total += len(wav) / tts.sample_rate
print(f"{OUT}: {min(count, len(replies))} clips, {total / 60:.1f} min")
if __name__ == "__main__":
make(int(sys.argv[1]) if len(sys.argv) > 1 else COUNT)
+298
View File
@@ -0,0 +1,298 @@
"""Always-on microphone: the head mic array (and a wireless clip mic if one is plugged in), cut into utterances.
Head array (AIUI-USB-MC): 8 channels at 16 kHz; channels 0-5 are the six mics of the ring, 6-7 are silent.
It is far from a speaker's mouth, so speech-to-text works better with a wireless clip mic (DJI Mic Mini):
when its receiver shows up as a sound card (EXTERNAL_NAMES), utterances are cut from the clip mic and their
text comes from it, while the head array keeps recording in parallel for the sound direction (doa.py): the
six-mic audio of the same time span is taken from a ring buffer. Choose with mic_source.txt: auto | head | clip.
An ALSA device can be opened only once, so everything that listens goes through here. An energy detector
cuts utterances: speech starts when the level stays above START_FACTOR x the background noise for
START_FRAMES frames and ends after END_SILENCE of quiet.
While Lumi itself speaks (mouth.py calls speaking()), the head array records nothing (the speaker is ~25x
louder than a voice there). The clip mic keeps listening (BARGE_IN): its utterances are marked during_speech, so
lumi.py can stop talking when the visitor says "stop" / "thanks" or asks something new.
python audio/mic.py # print every utterance: source, length, level and the direction
"""
import collections
import queue
import re
import subprocess
import threading
import time
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1] # the project folder
SOURCE_FILE = ROOT / "data" / "mic_source.txt"
DEVICE = "hw:CARD=AIUIUSBMC"
EXTERNAL_NAMES = r"DJI|Wireless|Mic Mini|MIC MINI|RX" # sound card names of a clip-mic receiver
RATE, CHANNELS, MICS = 16000, 8, slice(0, 6)
FRAME = 480 # 30 ms
START_FACTOR = 1.8 # speech = louder than START_FACTOR x background noise (2.5 missed
# people 4-5 m away: only 1 of 4 phrases was heard, 2026-10-12)
MIN_LEVEL = 250 # ... and at least this RMS (head array; room noise is ~180)
MIN_LEVEL_CLIP = 300 # ... (clip mic: close to the mouth, quiet room noise)
START_FRAMES = 4 # 120 ms of speech to start
END_LEVEL = 1.0 # quiet = below this x the start threshold (0.7 kept room noise ~180-250 "speech")
END_SILENCE = 0.6 # s of quiet that ends an utterance
MAX_UTTERANCE = 8.0 # s (12 s: in a room with music an utterance never got quiet enough
# to end, every one ran the full 12 s, 2026-10-21)
PRE_ROLL = 10 # frames kept before the start (300 ms)
AFTER_SPEAKING = 0.4 # s still ignored after Lumi stopped talking (room echo)
BARGE_IN = True # clip mic: keep listening while Lumi talks (interruptions)
RING_S = 20.0 # s of head-array audio kept for the sound direction of clip-mic utterances
class Utterance:
def __init__(self, mics, mono, t_start, t_end, peak, source, during_speech=False):
self.mics = mics # int16 (n, 6) head array (for doa), may be empty
self.mono = mono # int16 mono (for speech-to-text)
self.t_start, self.t_end, self.peak, self.source = t_start, t_end, peak, source
self.during_speech = during_speech # recorded while Lumi was talking (clip mic only)
@property
def seconds(self):
return len(self.mono) / RATE
class Segmenter:
"""Energy speech detector over 30 ms frames."""
def __init__(self, min_level):
self.min_level = min_level
self.levels = collections.deque(maxlen=300) # last 9 s of frame levels, for the noise floor
self.before = collections.deque(maxlen=PRE_ROLL)
self.frames, self.voiced, self.silent, self.peak = [], 0, 0, 0.0
self.in_speech, self.started = False, 0.0
self.noise = self.threshold = 0.0
def reset(self):
self.before.clear()
self.frames, self.voiced, self.in_speech = [], 0, False
def feed(self, frame, level, now):
"""Returns (frames, t_start, t_end, peak) when an utterance ended, else None."""
if not self.in_speech:
self.levels.append(level)
self.noise = float(np.percentile(self.levels, 30))
self.threshold = max(self.min_level, START_FACTOR * self.noise)
self.before.append(frame)
self.voiced = self.voiced + 1 if level > self.threshold else 0
if self.voiced >= START_FRAMES:
self.in_speech, self.started = True, now - (len(self.before) * FRAME / RATE)
self.frames, self.silent, self.peak = list(self.before), 0, level
return None
self.frames.append(frame)
self.peak = max(self.peak, level)
self.silent = self.silent + 1 if level < self.threshold * END_LEVEL else 0
if self.silent * FRAME / RATE >= END_SILENCE or now - self.started > MAX_UTTERANCE:
out = (self.frames, self.started, now, self.peak)
self.frames, self.voiced, self.in_speech = [], 0, False
self.before.clear()
return out
return None
def find_external():
"""ALSA name of a clip-mic receiver (e.g. DJI Mic Mini RX), or None."""
choice = SOURCE_FILE.read_text().strip().lower() if SOURCE_FILE.exists() else "auto"
if choice == "head":
return None
out = subprocess.run(["arecord", "-l"], capture_output=True, text=True).stdout
for m in re.finditer(r"card (\d+): (\S+) \[([^\]]*)\]", out):
num, short, long_ = m.groups()
if "AIUI" in short or "AIUI" in long_:
continue
if re.search(EXTERNAL_NAMES, short + " " + long_):
return f"plughw:CARD={short},DEV=0"
return None
class Mic(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.utterances = queue.Queue(maxsize=20)
self.ring = collections.deque(maxlen=int(RING_S * RATE / FRAME)) # (time, (480, 6) int16)
self.ring_lock = threading.Lock()
self.head_seg, self.clip_seg = Segmenter(MIN_LEVEL), Segmenter(MIN_LEVEL_CLIP)
self.external = None # ALSA device of the clip mic, when found
self.muted_until = 0.0
self.speaking_now = False
self.error = None
# the active detector's state (ears.py reads these)
@property
def seg(self):
return self.clip_seg if self.external else self.head_seg
@property
def in_speech(self):
return self.seg.in_speech
@property
def noise(self):
return self.seg.noise
@property
def threshold(self):
return self.seg.threshold
# ---------- used by mouth.py ----------
def speaking(self, on):
self.speaking_now = on
if not on:
self.muted_until = time.time() + AFTER_SPEAKING
def muted(self):
return self.speaking_now or time.time() < self.muted_until
# ---------- used by listeners ----------
def clear(self):
while not self.utterances.empty():
try:
self.utterances.get_nowait()
except queue.Empty:
break
def next(self, timeout):
try:
return self.utterances.get(timeout=timeout)
except queue.Empty:
return None
def _put(self, u):
try:
self.utterances.put_nowait(u)
except queue.Full: # nobody is reading: keep the newest
try:
self.utterances.get_nowait()
except queue.Empty:
pass
self.utterances.put_nowait(u)
def head_audio(self, t_start, t_end):
"""Six-mic audio recorded between two times (from the ring buffer)."""
with self.ring_lock:
frames = [x for t, x in self.ring if t_start <= t <= t_end + 0.05]
return np.concatenate(frames) if frames else np.zeros((0, 6), np.int16)
# ---------- recording threads ----------
def run(self):
threading.Thread(target=self._clip_loop, daemon=True).start()
while True:
try:
self._record_head()
except Exception as e:
self.error = repr(e)
time.sleep(1.0) # arecord ended (device gone?): start again
def _record_head(self):
proc = subprocess.Popen(["arecord", "-q", "-D", DEVICE, "-f", "S16_LE", "-r", str(RATE), "-c", str(CHANNELS),
"-t", "raw"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
nbytes = FRAME * CHANNELS * 2
try:
while True:
raw = proc.stdout.read(nbytes)
if len(raw) < nbytes:
return
x = np.frombuffer(raw, np.int16).reshape(-1, CHANNELS)[:, MICS]
now = time.time()
with self.ring_lock:
self.ring.append((now, x))
if self.external: # the clip mic cuts the utterances
continue
if self.muted(): # Lumi is talking: drop everything
self.head_seg.reset()
continue
level = float(np.sqrt(np.mean(x.astype(np.float32).mean(1) ** 2)))
done = self.head_seg.feed(x, level, now)
if done:
frames, t0, t1, peak = done
mics = np.concatenate(frames)
self._put(Utterance(mics, mics.astype(np.float32).mean(1).astype(np.int16), t0, t1, peak, "head"))
finally:
proc.kill()
def _clip_loop(self):
"""Look for a clip-mic receiver every few seconds; record from it while it is there."""
while True:
dev = find_external()
if not dev:
self.external = None
time.sleep(5.0)
continue
self.external = dev
try:
self._record_clip(dev)
except Exception as e:
self.error = repr(e)
self.external = None
time.sleep(2.0)
def _record_clip(self, dev):
proc = subprocess.Popen(["arecord", "-q", "-D", dev, "-f", "S16_LE", "-r", str(RATE), "-c", "1", "-t", "raw"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
nbytes = FRAME * 2
talking_since = None # Lumi started talking at (for during_speech)
try:
while True:
raw = proc.stdout.read(nbytes)
if len(raw) < nbytes:
return
x = np.frombuffer(raw, np.int16)
now = time.time()
if self.muted():
if not BARGE_IN:
self.clip_seg.reset()
continue
talking_since = talking_since or now
elif talking_since and not self.clip_seg.in_speech:
talking_since = None
level = float(np.sqrt(np.mean(x.astype(np.float32) ** 2)))
done = self.clip_seg.feed(x, level, now)
if done:
frames, t0, t1, peak = done
during = talking_since is not None and t1 >= talking_since
self._put(Utterance(self.head_audio(t0, t1), np.concatenate(frames), t0, t1, peak, "clip", during))
finally:
proc.kill()
_mic = None
_lock = threading.Lock()
def get():
"""The shared, running microphone."""
global _mic
with _lock:
if _mic is None:
_mic = Mic()
_mic.start()
return _mic
def speaking(on):
"""mouth.py: Lumi starts / stops talking (no-op if nothing listens in this program)."""
if _mic is not None:
_mic.speaking(on)
if __name__ == "__main__":
from audio import doa
m = get()
time.sleep(1.0)
print(f"listening on {'clip mic ' + m.external if m.external else 'the head array'} ... (Ctrl+C to stop)")
try:
while True:
u = m.next(1.0)
if u is None:
continue
ang = doa.estimate(u.mics) if len(u.mics) else (0.0, 0.0, 0.0)
print(f"[{u.source}] {u.seconds:4.1f} s peak {u.peak:5.0f} noise {m.noise:4.0f} "
f"direction {ang[0]:+5.0f} deg (confidence {ang[1]:.2f})")
except KeyboardInterrupt:
pass
+210
View File
@@ -0,0 +1,210 @@
"""Speaking: text -> speech (Supertonic-3, English and Korean, on the robot) -> USB speaker.
python audio/mouth.py "Hello, I am Lumi."
python audio/mouth.py "안녕하세요, 저는 루미예요."
Long answers are split into sentences: the next sentence is synthesised while the current one plays,
so Lumi starts talking after the first sentence is ready (about 1 s). say_stream() takes sentences while
they are still being written by the LLM, so speech starts before the whole answer exists.
Fixed phrases (greetings) are synthesised once and kept (CACHED), so they play at once.
While Lumi talks the microphone is muted (mic.speaking), so it never hears itself.
"""
import pathlib
import queue
import re
import subprocess
import sys
import threading
import time
import numpy as np
from audio import mic
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
DEVICE = "plughw:CARD=Device,DEV=0" # "USB Audio Device"
VOICE = "F1" # F1-F5 female, M1-M5 male
STEPS = 4 # quality/speed: 4 fast ... 8 best
SPEED = 0.92 # < 1 = slower; 1.05 sounded rushed
SPEED_MIN, SPEED_MAX = 0.72, 1.2 # what "speak slower / faster" may set (Supertonic takes 0.7 to 2.0)
SPLIT_WORDS = 8 # a first sentence this long is said in two parts, cut after its first
# comma: the first part is synthesised in ~0.7 s instead of ~1.8 s
VOLUME = 55 # % of the USB speaker mixer (100 % disturbed people in the office)
CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하세요, 저는 루미예요. 무엇을 도와드릴까요?",
"Yes?", "네?", "Okay, I'm coming.", "네, 갈게요.", "I'm right here.",
"Sorry, I can't get closer from here.", "How can I help you?", "무엇을 도와드릴까요?",
"Let me check.", "확인해 볼게요.", "Okay, I'll be quiet.", "네, 조용히 할게요.",
"Sorry, I'm not connected to the internet right now, so I can't look that up.",
"Yes? How can I help?", "네? 무엇을 도와드릴까요?",
"Welcome back! How can I help you?", "다시 오셨네요, 무엇을 도와드릴까요?", "Okay, I'm going to my charging dock.", "네, 충전소로 갈게요.",
"Sorry, driving is switched off."] + [f"Okay, I'm going to p{i}." for i in range(1, 11)]
_tts = None
_style = None
_cache = {}
_volume_set = False
_recent = [] # (time, sentence) Lumi said lately: to tell its own echo from a visitor
last_voice = 0.0 # time.time() when the last say_stream() began to play (lumi.py logs it)
def recent_speech(seconds=30.0):
"""What Lumi said in the last seconds (lumi.py ignores its own voice picked up by the clip mic).
Long sentences take 15 s and more to say, so the window is long."""
now = time.time()
return " ".join(t for when, t in _recent if now - when < seconds)
VOLUME_FILE = ROOT / "data" / "volume.txt" # set from the dashboard (api/server.py /volume); overrides VOLUME
def volume():
try:
return max(0, min(100, int(VOLUME_FILE.read_text().strip())))
except (FileNotFoundError, ValueError):
return VOLUME
def set_volume(percent=None):
"""Apply (and with percent: store) the speaker volume."""
if percent is not None:
VOLUME_FILE.write_text(str(int(max(0, min(100, percent)))))
subprocess.run(["amixer", "-q", "-c", "Device", "sset", "Speaker", f"{volume()}%"], check=False)
SPEED_FILE = ROOT / "data" / "speech_speed.txt" # set by voice ("speak slower", assistant/voice_words.py)
def speed():
try:
return max(SPEED_MIN, min(SPEED_MAX, float(SPEED_FILE.read_text().strip())))
except (FileNotFoundError, ValueError):
return SPEED
def set_speed(value):
"""Store the speaking speed; the cached fixed phrases were made at the old one, so they are made when said."""
SPEED_FILE.write_text(f"{max(SPEED_MIN, min(SPEED_MAX, value)):.2f}")
_cache.clear()
def _set_volume():
global _volume_set
if not _volume_set:
set_volume()
_volume_set = True
def _load():
global _tts, _style
_set_volume()
if _tts is None:
from supertonic import TTS
_tts = TTS(model="supertonic-3", model_dir=ROOT / "models/supertonic3", auto_download=False,
intra_op_num_threads=8)
_style = _tts.get_voice_style(VOICE)
return _tts
def lang_of(text):
return "ko" if re.search(r"[가-힣]", text) else "en"
def sentences(text):
parts = re.split(r"(?<=[.!?。!?])\s+", text.strip())
return [p for p in parts if p]
def first_parts(sentence):
"""A long first sentence cut after its first comma (3 words in or later), so the voice starts sooner."""
m = re.search(r"[,;]\s", sentence)
if len(sentence.split()) < SPLIT_WORDS or not m or len(sentence[:m.start()].split()) < 3:
return [sentence]
return [sentence[:m.start() + 1], sentence[m.end():]]
_play_lock = threading.Lock() # one sentence at a time (a skill's result is spoken from another thread)
def _play(wav, rate, abort=None):
"""Play; returns False if aborted."""
pcm = (np.clip(wav, -1, 1) * 32767).astype(np.int16).tobytes()
with _play_lock:
mic.speaking(True)
try:
return _play_pcm(pcm, rate, abort)
finally:
mic.speaking(False)
def _play_pcm(pcm, rate, abort):
p = subprocess.Popen(["aplay", "-q", "-D", DEVICE, "-f", "S16_LE", "-r", str(rate), "-c", "1", "-t", "raw"],
stdin=subprocess.PIPE)
def feed():
try:
p.stdin.write(pcm)
p.stdin.close()
except (BrokenPipeError, ValueError): # aplay was killed (abort)
pass
threading.Thread(target=feed, daemon=True).start()
while p.poll() is None:
if abort and abort():
p.kill()
return False
time.sleep(0.05)
return True
def _synth(text, lang):
if text in _cache:
return _cache[text]
wav, _ = _tts.synthesize(text, voice_style=_style, lang=lang, total_steps=STEPS, speed=speed())
return np.asarray(wav).reshape(-1)
def say_stream(pieces, lang=None, abort=None):
"""Speak text that arrives in pieces (e.g. sentences from a streaming LLM); returns the full text.
Synthesis of the next sentence runs while the current one plays."""
tts = _load()
rate = tts.sample_rate
q = queue.Queue() # unbounded: the synth thread always finishes
spoken = []
def synth():
try:
for piece in pieces:
for s in sentences(piece):
for part in [s] if spoken else first_parts(s):
spoken.append(part)
q.put((part, _synth(part, lang or lang_of(part))))
finally:
q.put(None)
global last_voice
threading.Thread(target=synth, daemon=True).start()
first = True
while (item := q.get()) is not None:
text, wav = item
if first:
last_voice, first = time.time(), False
_recent.append((time.time(), text))
del _recent[:-12]
if not _play(wav, rate, abort):
break
return " ".join(spoken)
def say(text, lang=None, abort=None):
"""Speak text and return when finished (or when abort() becomes True)."""
say_stream([text], lang, abort)
def warm_up():
"""Load the model, run it once so the first real sentence is fast, and prepare the fixed phrases."""
tts = _load()
tts.synthesize("Hi.", voice_style=_style, lang="en", total_steps=2)
for text in CACHED:
_cache[text] = _synth(text, lang_of(text))
if __name__ == "__main__":
say(" ".join(sys.argv[1:]) or "Hello, I am Lumi Robot Assistant. How can I help you?")
+48
View File
@@ -0,0 +1,48 @@
"""Split a song into vocals and accompaniment (Demucs htdemucs) for audio/sing_mine.py. Offline tool: runs only in
the separate render venv (.venv-songs, torch CPU + demucs), never in the robot's .venv.
.venv-songs/bin/python audio/separate.py data/songs/mine/BIGBANG_FANTASTIC_BABY.mp3
Writes <folder>/<name>/vocals.wav and <folder>/<name>/mr.wav (44.1 kHz stereo) next to the song.
"""
import pathlib
import sys
import numpy as np
import soundfile as sf
import torch
from demucs.apply import apply_model
from demucs.pretrained import get_model
MODEL = "htdemucs" # 4 stems: drums, bass, other, vocals
THREADS = 12 # CPU threads (the Thor has 14 cores; leave some for the robot's services)
def separate(path):
path = pathlib.Path(path)
out = path.with_suffix("")
out.mkdir(exist_ok=True)
torch.set_num_threads(THREADS)
model = get_model(MODEL)
model.eval()
wav, sr = sf.read(path, dtype="float32", always_2d=True)
assert sr == model.samplerate, (sr, model.samplerate)
x = torch.from_numpy(wav.T.copy())
if x.shape[0] == 1:
x = x.repeat(2, 1)
ref = x.mean(0)
mean, std = ref.mean(), ref.std()
with torch.no_grad():
stems = apply_model(model, ((x - mean) / std)[None], shifts=1, split=True, overlap=0.25, progress=True)[0]
stems = stems * std + mean
names = model.sources
vocals = stems[names.index("vocals")].numpy().T
mr = sum(stems[i] for i, n in enumerate(names) if n != "vocals").numpy().T
sf.write(out / "vocals.wav", np.clip(vocals, -1, 1), sr)
sf.write(out / "mr.wav", np.clip(mr, -1, 1), sr)
print(f"{out}/vocals.wav, mr.wav")
if __name__ == "__main__":
for p in sys.argv[1:]:
separate(p)
+378
View File
@@ -0,0 +1,378 @@
"""Singing: play a pre-rendered song (data/songs/<id>.wav, made by audio/sing_render.py, or data/songs/mine/<id>.wav,
made by audio/sing_mine.py from the owner's own files) and move the head with it.
python audio/sing.py # list the songs
python audio/sing.py twinkle # sing one (plays on the speaker and moves the head)
Each <id>.json holds the title, the names it is asked by and the lyrics; the public domain songs also the melody
and chords, the owner's songs (local only, never copied off the robot) their head moves timed to the beat. The song is played through mouth._play (the microphone is muted the same way as for speech,
and abort() stops it within 50 ms). The head turns to yaw 0 / pitch 0 and dances around it in a thread, following the
music: small diagonal bobs landing on the beats in energetic parts, a quick sweep with a dip on a bar's accent or a
phrase start, slower sways in calm parts, each move called early enough (the owner's measured head timing) to land
on its beat, one call at a time; it goes back to yaw 0 / pitch 0 when the song ends or is stopped. Never the lift, the waist or the arm.
"""
import json
import pathlib
import random
import re
import sys
import threading
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1]
SONGS = ROOT / "data" / "songs"
MINE = SONGS / "mine" # the owner's songs: local only
YAW_SWAY = 40.0 # deg; head yaw stays within +- this while singing (owner: wider, 2026-10-21)
PITCH_RANGE = (0.0, 28.0) # deg, absolute head pitch while singing (0 = level, + = up; owner: higher)
# head timing measured by the owner (2026-10-20, body API, vel = acc = 100, head.status polled every 20 ms): the head
# starts 0.2 s after the call and turns ~40 deg/s after that (15 / 6 deg diagonal reached at 0.87 s, 25 / 10 deg at
# 1.12 s); the call returns ~0.1 s after it arrives. Speed is no higher above vel 50. Overlapping moveto calls hang
# the body API: a move is sent only after the last one returned.
REACH_S = 0.5 # s from the call until a small move arrives (start delay + speeding up)
RETURN_S = 0.6 # s from the call until it returns, for a small move
HEAD_DEG_S = 40.0 # deg/s of the larger axis at vel >= VEL_FULL
VEL_FULL = 50 # speed ratio % from which the head is at its full speed
VEL_LIVELY, VEL_CALM, VEL_CALMEST = 100, 100, 80 # speed ratio %: energetic / calm / the calmest parts
ENERGETIC = 0.4 # music energy (0..1) from which the head bobs on the beat
CALMEST = 0.15 # below this energy the head sways slowly
BOB_DEG = (7.0, 12.0) # deg, a beat's bob (diagonal nod / tilt), alternating sides
ACCENT_DEG = (25.0, 38.0) # deg, a bar's or phrase's accent: a quick sweep with a dip
SWAY_DEG = (12.0, 20.0) # deg, a calm sway
ACCENT_EVERY_S = 1.2 # s, at least this between two accents
CENTRE_PITCH = 12.0 # deg; the dance moves around yaw 0, this pitch
GAP_S = 0.02 # s between a call returning and the next one
MIN_CHANGE = (1.5, 0.8) # deg; every move changes yaw and pitch at least this much
MIN_TURN_DEG = 20.0 # two moves in a row differ in direction by at least this (never one line)
HEAD_VEL = 70 # speed ratio % for turning to yaw 0 / pitch 0 before and after the song
LATE_S = 0.4 # s; a move this late is skipped (the previous one took longer)
RETURN_WAIT_S = 3.0 # s a new song waits for the head to get back from the last one
SING = re.compile(r"\bsing\b|\bsay (?:a |some )?songs?\b|" # whisper writes "let's say song"
r"\b(?:play|put on|turn on|start)(?: me| us)? (?:a |some |any |another |the |your )?(?:songs?|music|tunes?)\b|"
r"\b(?:another|different|next|new|other) (?:song|tune)\b|\b(?:want|like|love) to hear (?:a |some )?(?:song|music)\b|"
r"^\W*(?:lumi\W*)?(?:a |some )?(?:song|music)(?:\W+(?:please|lumi))*\W*$|"
r"(?:노래|음악|(?<![가-힣])곡)\s*(?:를|을|좀|하나|한\s*곡|한\s*번|한번|도|이나|나|이든|든|라도|\s)*"
r"(?:불러|부르|들려|해|틀어|틀|뽑아|부탁|재생|플레이|(?:할|부를)\s*(?:수|줄)\s*(?:있|알))|"
r"노래\s*(?:좀|하나)?\s*(?:듣고\s*싶|들을래|듣자)|(?:다른|딴|다음)\s*(?:노래|곡)|(?:다른|딴)\s*(?:거|걸|걸로)\s*(?:불러|들려|틀어)|^\W*(?:노래|음악)\s*(?:좀|하나)?\W*$", re.I)
SING_TITLE = re.compile(r"(불러|들려|틀어) ?(줘|주세요|줄래|봐|볼래)|\b(?:sing|play)\b") # "아리랑 불러 줘": a title said with it
SONG_LIST = re.compile(r"\b(?:what|which) (?:kinds? of |sort of |other )?(?:songs?|music|tunes)\b|\bwhat can you sing\b|"
r"\bsongs? (?:do |can |could )?you (?:know|sing|have)\b|\b(?:know|have) any (?:other )?songs\b|"
r"\b(?:list|names?) of (?:your |the )?songs\b|"
r"(?:무슨|어떤|뭔|어느)\s*(?:노래|곡)(?!\s*(?:이든|든|이나|나|라도))|노래\s*(?:는|를|은)?\s*(?:뭐|뭘|몇)|"
r"아는\s*노래|부를\s*(?:수\s*있는|줄\s*아는)\s*노래|노래\s*목록", re.I)
NOT_REQUEST = re.compile(r"\b(?:do|did) you (?:really )?(?:like|love|enjoy)\b|"
r"\bwho sings?\b|\bfavou?rite\b|좋아하는|좋아해|잘\s*(?:해|하|불러)", re.I)
# right after a song (or the list of songs): a short word switches or repeats it
AFTER_SONG = re.compile(r"^\W*(?:(?:lumi|ok|okay|no|nah|um|please|then|now|and)\W+)*(?:sing |play )?"
r"(?:another(?: one)?|(?:the )?next(?: one)?|a different one|something (?:else|different)|"
r"not (?:this|that)(?: one)?|(?:it |that )?again|one more(?: time)?|once more|more)"
r"(?:\W+(?:please|lumi))*\W*$|"
r"^\W*(?:루미야?\W*)?(?:아니\W*)?(?:(?:그거|그\s*노래|이거|이\s*노래)\s*말고(?:\s*(?:다른|딴)\s*(?:거|걸로|노래))?|"
r"(?:다른|딴)\s*(?:거|걸|걸로|것)|다음\s*(?:거|곡|노래)?|한\s*번\s*더|하나\s*더|다시|또)"
r"\s*(?:요|줘|해\s*줘|불러\s*줘|들려\s*줘|부탁해요?|해요|주세요)?\W*$", re.I)
AGAIN = re.compile(r"\bagain\b|\bone more time\b|\bonce more\b|한 ?번 ?더|다시", re.I)
ANOTHER = re.compile(r"\b(another|different|next|other)\b|\bsomething else\b|\bnot (this|that)\b|다른|딴|다음|말고", re.I)
STOP = re.compile(r"\b(stop|enough|halt|quiet|shh+)\b|멈춰|그만|스톱|정지|조용", re.I)
KOREAN = re.compile(r"\bkorean\b|한국", re.I)
ENGLISH = re.compile(r"\benglish\b|영어", re.I)
FILLER = {"sing", "a", "an", "the", "song", "songs", "me", "us", "for", "please", "lumi", "some", "something", "now", "again",
"one", "another", "different", "other", "next", "little", "short", "can", "you", "could", "would", "will", "to",
"it", "that", "this", "together", "with", "and", "your", "nice", "hey", "hi", "ok", "okay", "play", "music",
"in", "korean", "english", "else", "let's", "lets", "let", "go", "now", "pretty", "beautiful", "my", "kids",
"children", "children's", "cute", "fun", "favorite", "favourite", "of", "yours", "so", "just", "maybe", "then"}
UNKNOWN = {"en": "Sorry, I don't know that song yet. I can sing {}.", "ko": "그 노래는 아직 몰라요. {} 부를 수 있어요."}
LIST = {"en": "I can sing {}. Which one would you like?", "ko": "{} 부를 수 있어요. 어떤 노래 불러 드릴까요?"}
_head_thread = None
def songs():
"""{id: song} for every song with a rendered file; song["wav"] is its path."""
out = {}
for p in sorted(SONGS.glob("*.json")) + sorted(MINE.glob("*.json")):
if p.with_suffix(".wav").exists():
out[p.stem] = {**json.loads(p.read_text()), "wav": p.with_suffix(".wav")}
return out
def asked(text, last=""):
"""Do these words ask Lumi to sing ("sing a song", "노래 불러 줘", "sing Arirang", "다른 노래", "can you sing?")?
`last` is the assistant's answer just before (brain history): right after a song a short "another one" /
"again" / "그거 말고" is a song too, right after the list of songs also a title alone ("Arirang")."""
t = text or ""
if NOT_REQUEST.search(t) or SONG_LIST.search(t):
return False
if re.match(r"ACTION: (?:sing|none songs)\b", last or "") and AFTER_SONG.search(t):
return True
if (last or "").startswith("ACTION: none songs") and _title(t, songs()):
return True
return bool(SING.search(t)) or bool(SING_TITLE.search(t) and _title(t, songs()))
def list_asked(text):
""""What songs can you sing?", "무슨 노래 알아?": the titles are said."""
return bool(SONG_LIST.search(text or "")) and not NOT_REQUEST.search(text or "")
def stop_words(text):
return bool(STOP.search(text or ""))
def _title(text, all_songs):
low = (text or "").lower() # Latin names are whole words ("bad" is not in "badminton")
return next((sid for sid, s in all_songs.items()
if any(re.search(rf"(?<![a-z]){re.escape(n)}(?![a-z])", low) for n in s["names"])), None)
def _unknown_title(text):
"""A title was named that is not one of ours: 'sing Yesterday', '애국가 불러 줘'."""
words = re.findall(r"[a-z']+", (text or "").lower())
if "sing" in words:
after = [w for w in words[words.index("sing") + 1:] if w not in ("me", "us", "please", "lumi")]
if after and after[0] not in FILLER: # "sing yesterday"; "sing for everyone" is no title
return True
m = re.search(r"(\S+?)\s*(?:을|를)?\s*(?:좀\s*)?(?:불러|들려)", text or "")
return bool(m) and not re.search(r"노래|좀|곡|하나|루미|아무|뭐|뭔가|^(한|또|더|다시|거|걸|것)$", m.group(1))
def choose(text, lang="en", last=None):
"""The song to sing for these words, or None when they name a song we don't have. A named song first; the
last one again when asked; else any song (one in the language asked for: "a Korean song"), not the last."""
all_songs = songs()
named = _title(text, all_songs)
if named and not ANOTHER.search(text or ""):
return named
if not named and _unknown_title(text):
return None
if last in all_songs and AGAIN.search(text or "") and not ANOTHER.search(text or ""):
return last # "sing it again", "한 번 더"
want = "ko" if KOREAN.search(text or "") else "en" if ENGLISH.search(text or "") else None
pool = [sid for sid, s in all_songs.items() if want in (None, s["lang"]) and sid != last] or \
[sid for sid in all_songs if sid != last] or list(all_songs)
return random.choice(pool) if pool else None
def unknown_reply(lang, lines=UNKNOWN):
names = [s["title_ko" if lang == "ko" else "title"] for s in songs().values()]
joined = ", ".join(names[:-1]) + (" and " if lang == "en" else ", ") + names[-1] if len(names) > 1 else "".join(names)
return lines[lang].format(joined + ("" if lang == "en" else "를" if _no_final(names[-1]) else "을"))
def list_reply(lang):
"""Every title: "I can sing Arirang, ... and Love Attack. Which one would you like?"."""
return unknown_reply(lang, LIST)
def _no_final(word):
"""Korean: the last syllable has no final consonant (를 rather than 을)."""
c = ord(word[-1]) - 0xAC00
return not (0 <= c < 11172) or c % 28 == 0
def song_beats(song):
"""[(seconds, energy 0..1, accent 0..1, a sung phrase starts)] per beat. The owner's songs carry them from the
instrumental (loudness, onsets) and the vocal (phrases); for the others they come from the tempo and the melody:
the bar's first beat is the accent, a phrase starts after a rest or a long note, the intro is calm."""
if "beats" in song:
return [tuple(b) if len(b) == 4 else (b[0], b[1], 0.5, False) for b in song["beats"]]
spb = 60.0 / song["bpm"]
meter = song["meter"]
intro = song.get("intro_bars", 1) * meter
tokens = [t.split(":") for t in song["melody"].split() if t != "|"] * song.get("repeat", 1)
starts, beat, after_break = set(), 0.0, True
for syl, note, b in tokens:
if note != "r" and syl != "~" and after_break:
starts.add(int(round(intro + beat)))
after_break = note == "r" or float(b) >= 2
beat += float(b)
total = intro + int(beat)
return [(i * spb, 0.3 if i < intro else 0.65, 1.0 if i % meter == 0 else 0.3, i in starts) for i in range(total)]
def _speed(vel):
return HEAD_DEG_S * min(1.0, vel / VEL_FULL)
def reach_time(dy, dp, vel):
"""s from the call until the head arrives (the owner's measurements)."""
return REACH_S + max(abs(dy), abs(dp)) / _speed(vel)
def move_time(dy, dp, vel):
"""s from the call until moveto returns."""
return RETURN_S + max(abs(dy), abs(dp)) / _speed(vel)
def _turn(a, b):
"""deg between two move directions (0 = same line forward, 180 = straight back)."""
na, nb = np.hypot(*a), np.hypot(*b)
return float(np.degrees(np.arccos(np.clip(np.dot(a, b) / (na * nb + 1e-9), -1, 1))))
def _fit(v, d, lo, hi, least):
"""A step d from v of at least `least`, ending inside lo..hi (turned toward the middle when it would not)."""
d = d if abs(d) >= least else least * (1 if d >= 0 else -1)
if lo <= v + d <= hi:
return d
if lo <= v - d <= hi:
return -d
toward = 1 if v < (lo + hi) / 2 else -1
return toward * max(least, min(abs(d), hi - v if toward > 0 else v - lo))
def p_room(pp):
"""+1 when the pitch has more room upward, -1 when downward."""
lo, hi = PITCH_RANGE
return 1 if hi - pp >= pp - lo else -1
def _bend(py, pp, dy, dp, last):
"""The move (dy, dp) from (py, pp) made to change both axes (MIN_CHANGE), to turn away from the last move's
line (MIN_TURN_DEG) and to end inside the limits: as planned, with the pitch the other way, else bent to either
side."""
lo, hi = PITCH_RANGE
for side in (0, "flip", 1, -1, 2, -2):
if side == "flip": # a sweep back: rise where the last one fell, and the other way
dy2, dp2 = dy, -dp if abs(dp) >= 2 else (2.5 if p_room(pp) > 0 else -2.5)
elif side and last is not None: # add a part across the last move's direction
n = np.hypot(*last) + 1e-9
size = max(np.hypot(dy, dp), 3.0) * 0.6 * abs(side)
dy2, dp2 = dy - last[1] / n * size * np.sign(side), dp + last[0] / n * size * np.sign(side)
else:
dy2, dp2 = dy, dp
dy2, dp2 = _fit(py, dy2, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0]), _fit(pp, dp2, lo, hi, MIN_CHANGE[1])
if last is None or MIN_TURN_DEG <= _turn(last, (dy2, dp2)) <= 180 - MIN_TURN_DEG:
break
return dy2, dp2
def head_targets(song, seed=0):
"""[(call s, yaw deg, pitch deg, speed %)] around yaw 0 / pitch CENTRE_PITCH, each move timed to land ON a beat
(called reach_time before it) and never before the last call returned. Energetic parts: a small diagonal bob on
every beat that leaves time (alternating sides, vel 100), and on a bar's accent or a phrase start a quick 15-25
deg sweep with a dip. Calm parts: slower sways. Every move changes both axes and turns away from the last move's
line (_bend)."""
rng = random.Random(seed)
beats = song_beats(song)
lo, hi = PITCH_RANGE
y, p, free = 0.0, 0.0, 0.0 # the pose and when the last call returns (starts at 0 / 0)
side, last, last_accent, out, pending = rng.choice((-1, 1)), None, -9.0, [], False
for k, (t, e, accent, phrase) in enumerate(beats):
if t < 0.8: # the head is still turning to 0 / 0
continue
pending = pending or ((accent >= 0.7 or phrase) and t - last_accent >= ACCENT_EVERY_S and e >= 0.3)
if pending: # an accent waits for the first beat it fits on
kind, vel = "accent", VEL_LIVELY
elif e >= ENERGETIC:
kind, vel = "bob", VEL_LIVELY
else:
kind, vel = "sway", VEL_CALM if e >= CALMEST else VEL_CALMEST
if kind != "bob" or rng.random() < 0.85:
side = -side
if kind == "accent": # a sweep across to the other side, dipping
side = -1 if y > 0 else 1
ty = side * rng.uniform(*ACCENT_DEG) * 0.7 + 0.3 * y
tp = rng.choice((max(lo, min(p, CENTRE_PITCH + 2) - rng.uniform(6, 10)), min(hi, CENTRE_PITCH + rng.uniform(8, 14)))) # dip or lift
elif kind == "bob":
size = rng.uniform(*BOB_DEG)
ty = y + side * size * rng.uniform(0.7, 1.0)
tp = (p - size * 0.8 if p > CENTRE_PITCH else p + size * 0.8) + rng.uniform(-1, 1) # diagonal
else:
ty = side * rng.uniform(*SWAY_DEG)
tp = CENTRE_PITCH + rng.uniform(-8, 8)
ty -= 0.15 * y if kind == "bob" else 0.0 # bobs drift back toward the middle
dy, dp = _bend(y, p, ty - y, tp - p, last)
call = t - reach_time(dy, dp, vel) # lands on the beat
for _ in range(8): # too little time: a smaller move (an accent stays big)
if call >= free + GAP_S or max(abs(dy), abs(dp)) <= (ACCENT_DEG[0] if kind == "accent" else 3.0):
break
dy, dp = _bend(y, p, dy * 0.8, dp * 0.8, last)
call = t - reach_time(dy, dp, vel)
if last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
n = np.hypot(*last) + 1e-9 # still on the last line: a small step across it instead
for size in (4.0, -4.0, 6.0, -6.0, 2.5, -2.5):
dy = _fit(y, -last[1] / n * size, -YAW_SWAY, YAW_SWAY, MIN_CHANGE[0] + 0.2)
dp = _fit(p, last[0] / n * size, lo, hi, MIN_CHANGE[1] + 0.2)
if MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
break
call = t - reach_time(dy, dp, vel)
if call < free + GAP_S or last is not None and not MIN_TURN_DEG <= _turn(last, (dy, dp)) <= 180 - MIN_TURN_DEG:
continue # no time or no fitting move for this beat: a later one
out.append((round(float(call), 3), round(float(y + dy), 2), round(float(p + dp), 2), int(vel)))
free = call + move_time(dy, dp, vel)
last, y, p = (dy, dp), y + dy, p + dp
if kind == "accent":
last_accent, pending = t, False
return out
def _move_head(song, seed, stop, head_api):
"""Turn the head to yaw 0 / pitch 0, follow the head targets until the song ends or stop is set, then go back
to yaw 0 / pitch 0. One call at a time (each blocks until the head arrives)."""
try:
lift, waist, _, _ = head_api.status()
except Exception as e:
print(f"sing: head status failed: {e}")
return
t0 = time.time()
try:
head_api.moveto([lift, waist, 0.0, 0.0], VEL_LIVELY, VEL_LIVELY)
for t, yaw, pitch, vel in head_targets(song, seed):
while not stop.is_set() and time.time() - t0 < t:
stop.wait(0.02)
if stop.is_set():
break
if time.time() - t0 - t > LATE_S:
continue
head_api.moveto([lift, waist, yaw, pitch], vel, vel)
except Exception as e:
print(f"sing: head move failed: {e}")
finally:
try:
head_api.moveto([lift, waist, 0.0, 0.0], HEAD_VEL, HEAD_VEL)
except Exception as e:
print(f"sing: head return failed: {e}")
def sing(song_id, abort=None, play=None, head_api=None, load=None):
"""Sing one song; blocks until it ends (True) or abort() becomes True (False). The head returns in its own
thread, so a stop is at once. play / head_api / load are for tests (default: the speaker and the real head)."""
global _head_thread
from audio import mouth
if play is None:
mouth._set_volume()
play = mouth._play
if head_api is None:
from robot import head as head_api
if load is None:
import soundfile as sf
def load(path):
return sf.read(path, dtype="float32")
song = songs()[song_id]
wav, rate = load(song["wav"])
wav = np.asarray(wav)
if wav.ndim == 2: # the owner's songs are stereo; the speaker is one channel
wav = wav.mean(1)
if _head_thread is not None:
_head_thread.join(RETURN_WAIT_S) # the head is still going back from the last song
# the clip mic hears the song: its words are Lumi's own voice until 30 s after its end (mouth.recent_speech)
mouth._recent.append((time.time() + len(wav) / rate, song["lyrics"]))
stop = threading.Event()
_head_thread = threading.Thread(target=_move_head, args=(song, time.time(), stop, head_api), daemon=True)
_head_thread.start()
try:
return bool(play(wav, rate, abort))
finally:
stop.set()
if __name__ == "__main__":
if len(sys.argv) < 2:
for sid, s in songs().items():
print(f"{sid:24} {s['lang']} {s['title']}")
else:
print("finished" if sing(sys.argv[1]) else "stopped")
if _head_thread:
_head_thread.join()
+316
View File
@@ -0,0 +1,316 @@
"""Make Lumi sing the best part of a song the owner provided (data/songs/mine/, local only, never copied to the Mac):
the singer's own vocal turned into Lumi's voice (audio/cover.py), over the song's instrumental.
.venv-songs/bin/python audio/separate.py data/songs/mine/<NAME>.mp3 # 1. vocals / instrumental (Demucs)
.venv-cover/bin/python audio/cover.py <NAME> # 2. the vocal in Lumi's voice
.venv/bin/python audio/sing_mine.py <NAME> --title "..." --title-ko "..." --names "a,b" # 3. this
3 does: words and their times from the separated vocal (whisper.cpp), the part to sing (~40-60 s where the
most-repeated lines, the singing and the loudness are; or --start/--end seconds), the beats of the instrumental for
the head moves, and the mix: Lumi's vocal at the singer's level with a little room reverb over the instrumental.
Writes data/songs/mine/<NAME>.wav (the part) + .json (audio/sing.py plays them) and <NAME>/full_lumi.wav (the
whole song, to check). Lyrics only ever go into data/songs/mine/.
"""
import argparse
import difflib
import json
import pathlib
import re
import subprocess
import numpy as np
import soundfile as sf
from audio import sing_render as R
ROOT = pathlib.Path(__file__).resolve().parents[1]
MINE = ROOT / "data" / "songs" / "mine"
WHISPER_CLI = ROOT / "whisper.cpp/build/bin/whisper-cli"
WHISPER_MODEL = ROOT / "models/ggml-large-v3-turbo-q5_0.bin"
SR = R.SR
PART_S = (40.0, 60.0) # s, length of the part sung
PART_BEST_S = 50.0 # s, preferred length
PAUSE_S = 0.2 # s of a quiet vocal between two sung phrases
PHRASE_LEVEL = 0.3 # vocal RMS below this part of its loud level counts as quiet (separated vocals
# keep some reverb and bleed, so not much lower)
MAX_PHRASE_S = 12.0 # s; a longer phrase is split at its quietest moment
CHUNK_S = 28.0 # s, longest piece of vocal given to whisper at once
SAME_LINE = 0.7 # difflib ratio: two lines are the same line (a repeat)
HOP = 441 # samples (10 ms) for pitch and energy frames
FRAME = 2048 # samples, pitch window
VOCAL_F0 = (70.0, 1000.0) # Hz, singer pitch range searched
VOICED_R = 0.6 # normalised autocorrelation above this = a sung (voiced) frame
VOICE_GAIN = 1.0 # Lumi's vocal level relative to the singer's in the record (1 = the same balance)
FADE_IN_S, FADE_OUT_S = 0.3, 2.5
BPM_RANGE = (70.0, 180.0)
BEAT_TIGHTNESS = 100.0 # DP beat tracker: how strongly beats keep the tempo
ENERGY_RANGE = (0.3, 0.8) # instrumental loudness (part of the song's loud level) mapped to energy 0 .. 1
BEAT_MIN = 0.6 # a beat closer than this part of the usual beat to the last one is a tracking hiccup
# ---------- analysis ----------
def mono(x):
return x.mean(1) if x.ndim == 2 else x
def frames(x, size, hop):
n = 1 + max(0, (len(x) - size) // hop)
idx = np.arange(size)[None, :] + hop * np.arange(n)[:, None]
return x[idx]
def rms(x, hop=HOP):
return np.sqrt((frames(x, hop * 2, hop) ** 2).mean(1) + 1e-12)
def pitch_contour(v):
"""Per 10 ms: f0 in Hz (0 = unvoiced) of a separated vocal; octave jumps of single frames removed."""
lo, hi = int(SR / VOCAL_F0[1]), int(SR / VOCAL_F0[0])
f = frames(np.pad(v, (FRAME // 2, FRAME)), FRAME, HOP)
e = np.sqrt((f ** 2).mean(1))
spec = np.fft.rfft(f * np.hanning(FRAME), 2 * FRAME)
ac = np.fft.irfft(np.abs(spec) ** 2)[:, :hi + 1]
ac /= ac[:, :1] + 1e-12
lag = lo + np.argmax(ac[:, lo:hi], 1)
best = ac[np.arange(len(ac)), lag]
# prefer the shortest lag that is nearly as good (the true period, not a multiple)
for div in (3, 2):
sub = np.round(lag / div).astype(int)
ok = (sub >= lo) & (ac[np.arange(len(ac)), np.clip(sub, 0, hi)] > 0.9 * best)
lag = np.where(ok, sub, lag)
f0 = np.where((best > VOICED_R) & (e > 0.1 * np.percentile(e, 95)), SR / lag, 0.0)
st = np.where(f0 > 0, 12 * np.log2(np.maximum(f0, 1) / 440), np.nan)
med = st.copy()
for i in range(2, len(st) - 2): # median of 5 frames
w = st[i - 2:i + 3]
w = w[~np.isnan(w)]
med[i] = np.median(w) if len(w) >= 3 and not np.isnan(st[i]) else np.nan
return np.where(np.isnan(med), 0.0, 440 * 2 ** (med / 12))
def onset_envelope(x):
"""Spectral flux per 10 ms frame (log magnitude, positive changes)."""
f = frames(x, 2048, HOP)
mag = np.log1p(100 * np.abs(np.fft.rfft(f * np.hanning(2048), axis=1)))
flux = np.maximum(0, np.diff(mag, axis=0)).sum(1)
flux = np.concatenate([[0], flux])
flux -= np.convolve(flux, np.ones(50) / 50, "same") # local mean removed
return np.maximum(flux, 0)
def beats(x):
"""(bpm, beat times s) of the instrumental: tempo from the onset autocorrelation, beats by dynamic
programming (Ellis 2007)."""
env = onset_envelope(x)
fps = SR / HOP
lags = np.arange(int(fps * 60 / BPM_RANGE[1]), int(fps * 60 / BPM_RANGE[0]) + 1)
ac = np.array([np.dot(env[:-l], env[l:]) for l in lags])
prior = np.exp(-0.5 * (np.log2(60 * fps / lags / 120.0) / 0.9) ** 2) # a mild preference for ~120 bpm
period = lags[np.argmax(ac * prior)]
score = env.copy()
back = np.full(len(env), -1)
span = np.arange(-2 * period, -period // 2)
cost = -BEAT_TIGHTNESS * np.log(-span / period) ** 2
for i in range(2 * period, len(env)):
c = score[i + span] + cost
k = np.argmax(c)
score[i] += c[k]
back[i] = i + span[k]
i = len(env) - period + np.argmax(score[-period:])
out = []
while i >= 0:
out.append(i)
i = back[i]
return 60 * fps / period, np.array(out[::-1]) / fps
def phrases(v):
"""[(t0, t1)] sung phrases of the separated vocal: parts between pauses of PAUSE_S."""
e = rms(v)
on = e > PHRASE_LEVEL * np.percentile(e, 95)
out, start, quiet = [], None, 0
for i, o in enumerate(on):
if o:
if start is None:
start = i
quiet = 0
elif start is not None:
quiet += 1
if quiet * 0.01 >= PAUSE_S:
out.append((start / 100, (i - quiet + 1) / 100))
start, quiet = None, 0
if start is not None:
out.append((start / 100, len(on) / 100))
out = [(a, b) for a, b in out if b - a >= 0.3]
done = []
while out:
a, b = out.pop(0)
if b - a <= MAX_PHRASE_S:
done.append((a, b))
continue
lo, hi = int((a + (b - a) / 4) * 100), int((b - (b - a) / 4) * 100)
cut = (lo + int(np.argmin(np.convolve(e[lo:hi], np.ones(15) / 15, "same")))) / 100
out[:0] = [(a, cut), (cut, b)]
return done
def whisper_words(v, folder, lang):
"""[(t0, t1, word)] of the separated vocal. whisper.cpp (one word per segment, DTW timestamps) on chunks of
whole phrases up to CHUNK_S: on a whole song at once it skips parts and drifts."""
chunks, cur = [], None
for a, b in phrases(v):
if cur and b - cur[0] <= CHUNK_S:
cur = (cur[0], b)
else:
if cur:
chunks.append(cur)
cur = (a, b)
chunks += [cur] if cur else []
words = []
tmp = folder / "chunk.wav"
for a, b in chunks:
a0 = max(0.0, a - 0.3)
sf.write(tmp, v[int(a0 * SR):int((b + 0.3) * SR)], SR)
subprocess.run(["sox", str(tmp), "-r", "16000", "-c", "1", "-b", "16", str(tmp.with_name("chunk16.wav"))],
check=True)
subprocess.run([str(WHISPER_CLI), "-m", str(WHISPER_MODEL), "-f", str(tmp.with_name("chunk16.wav")), "-l", lang,
"-ml", "1", "-sow", "-mc", "0", "-dtw", "large.v3.turbo", "-oj", "-of", str(folder / "chunk"),
"-np"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
words += [(t0 + a0, t1 + a0, w) for t0, t1, w in read_words(folder / "chunk.json") if t0 + a0 < b + 0.2]
(folder / "words.json").write_text(json.dumps(words, ensure_ascii=False))
for f in ("chunk.wav", "chunk16.wav", "chunk.json"):
(folder / f).unlink(missing_ok=True)
return words
def read_words(path):
"""whisper.cpp's JSON with one word per segment. A Korean character can be split over two segments (its UTF-8
bytes): such segments are joined."""
segs = json.loads(path.read_bytes().decode("utf-8", "surrogateescape"))["transcription"]
words, buf, t0 = [], b"", None
for s in segs:
if not buf:
t0 = s["offsets"]["from"] / 1000
buf += s["text"].encode("utf-8", "surrogateescape")
try:
w = buf.decode("utf-8").strip()
except UnicodeDecodeError:
continue
buf = b""
if w and not re.fullmatch(r"[\W_]*|\[.*\]|\(.*\)", w):
words.append((t0, s["offsets"]["to"] / 1000, w))
return words
def pick_part(words, phr, mr, vocal_f0):
"""(start s, end s): a part PART_S long, starting and ending with a sung phrase, where repeated lines (the
chorus), singing and a loud instrumental are."""
texts = [re.sub(r"\W", "", "".join(w for t, _, w in words if a - 0.2 <= t < b)).lower() for a, b in phr]
rep = np.array([sum(len(a) > 3 and difflib.SequenceMatcher(None, a, b).ratio() > SAME_LINE
for j, b in enumerate(texts) if j != i) for i, a in enumerate(texts)], float)
loud = rms(mr)
loud /= np.percentile(loud, 95)
voiced = vocal_f0 > 0
best, part = -1.0, (phr[0][0], phr[0][0] + PART_BEST_S)
for i in range(len(phr)):
for j in range(i, len(phr)):
t0, t1 = phr[i][0], phr[j][1]
if t1 - t0 > PART_S[1]:
break
if t1 - t0 < PART_S[0]:
continue
f0, f1 = int(t0 * 100), int(t1 * 100)
score = (1 + rep[i:j + 1].mean()) * (0.5 + voiced[f0:f1].mean()) * (0.5 + loud[f0:f1].mean()) \
* (1 + 0.3 * min(rep[i], 2)) * np.exp(-abs(t1 - t0 - PART_BEST_S) / 30) # begins with a repeated line
if score > best:
best, part = score, (t0, t1)
return part
# ---------- mix ----------
def beat_info(beat_times, mr, v, t_start, t_end):
"""[[s from the part's start, energy 0..1, accent 0..1, a sung phrase starts]] per beat of the part, for the
head moves of audio/sing.py: energy = the instrumental's loudness over half a second against the whole
song's (ENERGY_RANGE), accent = its strongest
onset within 60 ms of the beat, phrase = a vocal phrase begins before the next beat."""
loud = rms(mono(mr))
onset = onset_envelope(mono(mr))
bt = beat_times[(beat_times >= t_start) & (beat_times < t_end - 0.5)]
if not len(bt):
return []
period = np.median(np.diff(bt)) if len(bt) > 1 else 0.5
keep = [bt[0]]
for t in bt[1:]:
if t - keep[-1] > BEAT_MIN * period:
keep.append(t)
bt = np.array(keep)
energy = np.array([loud[int(t * 100):int(t * 100) + 50].mean() for t in bt]) / np.percentile(loud, 95)
energy = np.clip((energy - ENERGY_RANGE[0]) / (ENERGY_RANGE[1] - ENERGY_RANGE[0]), 0, 1)
accent = np.array([onset[max(0, int(t * 100) - 6):int(t * 100) + 7].max() for t in bt])
accent = np.clip(accent / (np.percentile(accent, 90) + 1e-9), 0, 1)
starts = np.array([a for a, _ in phrases(v)])
phrase = [bool(((starts >= t - 0.1) & (starts < t + period - 0.1)).any()) for t in bt]
return [[round(float(t - t_start), 3), round(float(e), 2), round(float(a), 2), ph]
for t, e, a, ph in zip(bt, energy, accent, phrase)]
def active_rms(x, ref):
"""RMS of x over the frames where it sounds (above 10 % of ref's loud level)."""
e = rms(x)
on = e > 0.1 * np.percentile(rms(ref), 95)
return float(np.sqrt((e[on] ** 2).mean())) if on.any() else 1e-9
def make(name, title, title_ko, names, lang, start=None, end=None):
folder = MINE / name
vocals, sr = sf.read(folder / "vocals.wav", dtype="float32", always_2d=True)
mr, _ = sf.read(folder / "mr.wav", dtype="float32", always_2d=True)
lumi, sr_l = sf.read(folder / "vocal_lumi.wav", dtype="float32", always_2d=True)
assert sr == SR and sr_l == SR, (sr, sr_l)
v, lumi = mono(vocals), mono(lumi)
f0 = pitch_contour(v)
words_file = folder / "words.json"
words = [tuple(w) for w in json.loads(words_file.read_text())] if words_file.exists() else \
whisper_words(v, folder, lang)
phr = phrases(v)
bpm, bt = beats(mono(mr))
if start is None:
start, end = pick_part(words, phr, mono(mr), f0)
bar = 4 * 60 / bpm
before = bt[bt <= start - 0.2]
t_start = float(before[-1] if len(before) and start - before[-1] < bar + 0.3 else max(0.0, start - 0.5))
if start - t_start < bar * 0.75 and len(before) > 4: # a bar of music before Lumi starts
t_start = float(bt[max(0, len(before) - 5)])
t_end = min(len(mr) / SR, end + 1.5)
n = min(len(lumi), len(mr))
voice = np.zeros(len(mr), np.float32)
voice[:n] = lumi[:n] * VOICE_GAIN * active_rms(v, v) / active_rms(lumi, v)
full = R.reverb(voice)[:, None] + mr
full *= 0.9 / np.abs(full).max()
sf.write(folder / "full_lumi.wav", full.astype(np.float32), SR, subtype="PCM_16")
part = full[int(t_start * SR):int(t_end * SR)].copy()
fi, fo = int(FADE_IN_S * SR), int(FADE_OUT_S * SR)
part[:fi] *= np.linspace(0, 1, fi)[:, None]
part[-fo:] *= np.linspace(1, 0, fo)[:, None]
sf.write(MINE / f"{name}.wav", part.astype(np.float32), SR, subtype="PCM_16")
lyrics = " ".join(w for a, _, w in words if start - 0.05 <= a < end)
song = {"title": title, "title_ko": title_ko, "lang": lang, "names": names,
"source": "owner's file; company holds the performance licence; local only",
"part_s": [round(t_start, 2), round(t_end, 2)], "bpm": round(bpm, 1),
"lyrics": lyrics, "beats": beat_info(bt, mr, v, t_start, t_end)}
(MINE / f"{name}.json").write_text(json.dumps(song, ensure_ascii=False, indent=1))
print(f"{MINE / name}.wav part {t_start:.1f}-{t_end:.1f} s ({t_end - t_start:.0f} s), {bpm:.0f} bpm; "
f"{folder / 'full_lumi.wav'}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("name")
ap.add_argument("--title", required=True)
ap.add_argument("--title-ko", required=True)
ap.add_argument("--names", required=True, help="comma-separated words it is asked by")
ap.add_argument("--lang", default="ko")
ap.add_argument("--start", type=float)
ap.add_argument("--end", type=float)
a = ap.parse_args()
make(a.name, a.title, a.title_ko, [n.strip().lower() for n in a.names.split(",")], a.lang, a.start, a.end)
+321
View File
@@ -0,0 +1,321 @@
"""Render the songs in data/songs/ once: Lumi's TTS voice sung to the melody over a backing track made here.
python audio/sing_render.py # every song
python audio/sing_render.py arirang # one song
Each syllable is spoken by the TTS (Supertonic-3, the same voice as every answer), its pitch is set to the note
and its vowel stretched to the note's length with a pitch-synchronous overlap-add (TD-PSOLA, written below: no
pyworld / librosa on this Thor). The backing (bass + chords, a soft piano-like tone) is synthesised from the
song's chord list. Voice and backing are mixed into data/songs/<id>.wav, which audio/sing.py plays.
Nothing here is downloaded: the melodies and chords are written in the song files (public domain songs).
"""
import json
import pathlib
import sys
import numpy as np
import soundfile as sf
ROOT = pathlib.Path(__file__).resolve().parents[1]
SONGS = ROOT / "data" / "songs"
SR = 44100 # Hz, the TTS sample rate
TARGET_MEAN_HZ = 240.0 # songs are transposed so their average note is near this (voice F1 speaks at ~175 Hz)
F0_RANGE = (110.0, 400.0) # Hz, pitch search range for the speaking voice
HOP = 220 # samples (5 ms) between pitch frames
WIN = 1323 # samples (30 ms) pitch analysis window
VOICED_R = 0.5 # normalised autocorrelation above this = voiced frame
UNVOICED_P = SR // 200 # samples; grain spacing in unvoiced parts
ONSET_MAX_S = 0.12 # s; a syllable's leading consonant is sung before the beat by up to this
GLIDE_S = 0.03 # s; pitch moves between notes with this time constant
VIBRATO = (5.5, 0.25, 0.3) # Hz, semitones depth, s from a note's start before the vibrato grows
NOTE_FILL = 0.92 # part of a note's length the syllable lasts (a short breath between notes)
VOICE_GAIN, BACKING_GAIN = 0.8, 0.22
REVERB_S, REVERB_MIX = 0.9, 0.12
NOTE_NAMES = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
CHORDS = {"": (0, 4, 7), "m": (0, 3, 7), "7": (0, 4, 7, 10), "m7": (0, 3, 7, 10)}
# ---------- song file ----------
def midi(name):
"""'F#4' -> 66"""
n = NOTE_NAMES[name[0]] + name[1:-1].count("#") - name[1:-1].count("b")
return 12 * (int(name[-1]) + 1) + n
def hz(m):
return 440.0 * 2 ** ((m - 69) / 12)
def notes(song):
"""[(start beat, beats, midi or None, syllable)] from 'syl:NOTE:beats' tokens ('-:r:1' rest, '~' slur);
the melody is played song['repeat'] times."""
out, beat = [], 0.0
tokens = [t for t in song["melody"].split() if t != "|"]
for _ in range(song.get("repeat", 1)):
for tok in tokens:
syl, note, beats = tok.split(":")
beats = float(beats)
out.append((beat, beats, None if note == "r" else midi(note), syl))
beat += beats
return out
def transpose(song):
"""Semitones that bring the song's average note to TARGET_MEAN_HZ (or the file's own 'transpose')."""
if "transpose" in song:
return song["transpose"]
ms = [m for _, _, m, _ in notes(song) if m is not None]
return round(12 * np.log2(TARGET_MEAN_HZ / hz(np.mean(ms))))
def chord_notes(name):
"""'F#m7' -> (root pitch class, intervals)"""
root = NOTE_NAMES[name[0]]
rest = name[1:]
if rest[:1] in ("#", "b"):
root += 1 if rest[0] == "#" else -1
rest = rest[1:]
return root % 12, CHORDS[rest]
# ---------- voice: pitch analysis and PSOLA ----------
def trim(x, level=0.02):
e = np.sqrt(np.convolve(x ** 2, np.ones(441) / 441, "same"))
on = np.nonzero(e > level * max(e.max(), 1e-9) / 0.3)[0]
return x[max(0, on[0] - 220):on[-1] + 220] if len(on) else x
def f0_track(x):
"""Per HOP frame: period in samples (0 = unvoiced)."""
lo, hi = int(SR / F0_RANGE[1]), int(SR / F0_RANGE[0])
rms_all = np.sqrt((x ** 2).mean())
periods = []
for i in range(0, max(1, len(x) - WIN), HOP):
f = x[i:i + WIN]
if len(f) < WIN or np.sqrt((f ** 2).mean()) < 0.3 * rms_all:
periods.append(0)
continue
spec = np.fft.rfft(f * np.hanning(WIN), 4096)
ac = np.fft.irfft(np.abs(spec) ** 2)[:hi + 1]
ac /= ac[0] + 1e-12
best = lo + np.argmax(ac[lo:hi])
periods.append(best if ac[best] > VOICED_R else 0)
p = np.array(periods, float)
sm = p.copy() # median of 5 frames removes single octave jumps
for i in range(2, len(p) - 2):
win = p[i - 2:i + 3]
sm[i] = np.median(win) if np.count_nonzero(win) >= 3 else 0
return sm
def pitch_marks(x, per):
"""Analysis marks [(sample, period)]: one per pitch period on voiced parts, every UNVOICED_P elsewhere."""
marks, t = [], 0
sign = 1 if x.max() >= -x.min() else -1
while t < len(x):
p = per[min(len(per) - 1, t // HOP)]
if p:
p = int(p)
a, b = max(0, t - p // 3), min(len(x), t + p // 3 + 1)
t = a + int(np.argmax(sign * x[a:b])) if b > a else t
marks.append((t, p))
t += p
else:
marks.append((t, UNVOICED_P))
t += UNVOICED_P
return marks
def voiced_span(per):
v = np.nonzero(per)[0]
return (v[0] * HOP, v[-1] * HOP + WIN) if len(v) else (0, 0)
def sing_syllable(x, pitches, dur):
"""x (a spoken syllable) sung for dur seconds on pitches [(seconds, Hz)] (one note, or a slur over several).
Returns (audio, onset seconds: the consonant before the vowel, to be placed before the beat)."""
per = f0_track(x)
va, vb = voiced_span(per)
if vb <= va: # nothing voiced (a whispered syllable): just fit the length
va, vb = 0, len(x)
va, vb = min(va, len(x)), min(vb, len(x))
n_out = int(dur * SR)
onset = min(va, int(ONSET_MAX_S * SR))
head, tail = va, len(x) - vb # consonants before / after the vowel keep their speed
body_out = n_out + onset - head - tail
if body_out < 0.3 * (vb - va): # too short a note: squeeze everything evenly
scale = (n_out + onset) / len(x)
def src(t):
return t / scale
else:
def src(t):
if t < head:
return t
if t < head + body_out:
return va + (t - head) * (vb - va) / body_out
return vb + (t - head - body_out)
total = n_out + onset
# target pitch along the output: notes in order, smoothed (glide) with a vibrato that grows into long notes
f0 = np.zeros(total)
ends = head + (np.cumsum([sec for sec, _ in pitches]) * SR).astype(int)
starts = [head] + list(ends[:-1])
for i in range(len(pitches)):
f0[0 if i == 0 else starts[i]:total if i == len(pitches) - 1 else ends[i]] = pitches[i][1]
alpha = 1 - np.exp(-1 / (GLIDE_S * SR))
log_f = np.log(f0)
sm = np.empty_like(log_f)
acc = log_f[0]
for i in range(0, total, 64): # smoothing in blocks of 64 samples is plenty
acc += (log_f[i] - acc) * (1 - (1 - alpha) ** 64)
sm[i:i + 64] = acc
t = np.arange(total) / SR
note_start = np.zeros(total)
for a in starts:
note_start[a:] = a / SR
since = np.clip(t - note_start - VIBRATO[2], 0, None)
vib = VIBRATO[1] * np.minimum(1, since / 0.3) * np.sin(2 * np.pi * VIBRATO[0] * t)
target = np.exp(sm) * 2 ** (vib / 12)
# TD-PSOLA: grains two input periods long, placed at the target period
marks = pitch_marks(x, per)
pos = np.array([m for m, _ in marks])
y, w = np.zeros(total + 2 * SR // 50), np.zeros(total + 2 * SR // 50)
out = 0
while out < total:
s = src(out)
k = int(np.argmin(np.abs(pos - s)))
m, p = marks[k]
voiced = va <= s < vb and p != UNVOICED_P
win = np.hanning(2 * p + 1)
a, b = m - p, m + p + 1
grain = np.zeros(2 * p + 1)
ga, gb = max(0, a), min(len(x), b)
grain[ga - a:gb - a] = x[ga:gb]
oa = out - p
lo = max(0, oa)
hi = min(len(y), oa + 2 * p + 1)
if hi > lo:
y[lo:hi] += (grain * win)[lo - oa:hi - oa]
w[lo:hi] += win[lo - oa:hi - oa]
out += max(20, int(SR / target[min(out, total - 1)])) if voiced else p
y = y[:total] / np.maximum(w[:total], 0.5)
fade = int(0.01 * SR)
fade = min(fade, len(y) // 4) # a very short syllable (fast rap) gets shorter fades
y[:fade] *= np.linspace(0, 1, fade)
y[len(y) - fade * 3:] *= np.linspace(1, 0, fade * 3)
return y, onset / SR
def segments(song, shift):
"""Sung syllables [(start s, seconds, syllable, [(seconds, Hz)])]: a syllable and the slurs ('~') after it."""
spb = 60.0 / song["bpm"]
intro = song.get("intro_bars", 1) * song["meter"] * spb
out = []
for beat, beats, m, syl in notes(song):
sec = beats * spb
if m is None:
continue
if syl == "~" and out:
out[-1][1] += sec
out[-1][3].append((sec, hz(m + shift)))
else:
out.append([intro + beat * spb, sec, syl, [(sec, hz(m + shift))]])
return out
def render_voice(song, shift, n):
from audio import mouth
tts = mouth._load()
assert tts.sample_rate == SR, tts.sample_rate
lang = song["lang"]
spoken = {}
y = np.zeros(n)
for start, sec, syl, pitches in segments(song, shift):
if syl not in spoken:
spoken[syl] = trim(np.asarray(mouth._synth(syl, lang), float))
dur = sec * NOTE_FILL if sec > 0.3 else sec * 0.97
v, onset = sing_syllable(spoken[syl], pitches, dur)
a = max(0, int((start - onset) * SR))
b = min(n, a + len(v))
y[a:b] += v[:b - a]
return y
# ---------- backing ----------
def tone(f, sec, bright=1.0, decay=2.5):
"""A soft plucked / piano-like note."""
t = np.arange(int(sec * SR)) / SR
y = sum(np.sin(2 * np.pi * f * k * t) * bright ** (k - 1) / k ** 1.6 * np.exp(-t * decay * (1 + 0.5 * k))
for k in range(1, 7))
y *= np.minimum(1, t / 0.006)
return y
def render_backing(song, shift, n):
"""Bass on the bar's first beat (and the middle in 4/4 and 6/8), the chord on the other beats; one chord per
bar, or 'C,G' for two."""
spb = 60.0 / song["bpm"]
meter = song["meter"]
bars = song["chords"].split() * song.get("repeat", 1)
bars = [bars[0]] * song.get("intro_bars", 1) + bars + [bars[-1]] # count-in bar and a last ringing bar
strong = {3: (0,), 4: (0, 2), 6: (0, 3)}[meter]
y = np.zeros(n)
for i, bar in enumerate(bars):
parts = bar.split(",")
for beat in range(meter):
name = parts[min(len(parts) - 1, beat * len(parts) // meter)]
root, iv = chord_notes(name)
t = (i * meter + beat) * spb
a = int(t * SR)
last = i == len(bars) - 1
if last and beat:
break
ring = meter * spb if last else spb * 1.2
f = hz(36 + (root + shift) % 12) # bass, C2..B2
bass = 0.9 * tone(f, ring * 1.5, 0.4, 1.5) + 0.3 * tone(f * 2, ring * 1.5, 0.3, 2.0)
chord = sum(tone(hz(55 + (root + shift + k - 7) % 12), ring, 0.6, 3.0) for k in iv) * 0.45 # G3..F#4
if last:
v = bass[:len(chord)] + chord
else:
v = bass if beat in strong else chord
b = min(n, a + len(v))
y[a:b] += v[:b - a]
return y
def reverb(x):
"""Convolution with a short decaying noise tail (a small room)."""
rng = np.random.default_rng(1)
t = np.arange(int(REVERB_S * SR)) / SR
ir = rng.standard_normal(len(t)) * np.exp(-t * 6.9 / REVERB_S)
ir[:int(0.02 * SR)] = 0
ir /= np.sqrt((ir ** 2).sum())
size = 1 << int(np.ceil(np.log2(len(x) + len(ir))))
wet = np.fft.irfft(np.fft.rfft(x, size) * np.fft.rfft(ir, size), size)[:len(x)]
return x + REVERB_MIX * wet
def length_s(song):
beats = sum(b for _, b, _, _ in notes(song))
return (song.get("intro_bars", 1) * song["meter"] + beats + song["meter"]) * 60.0 / song["bpm"] + 1.0
def render(song_id):
song = json.loads((SONGS / f"{song_id}.json").read_text())
shift = transpose(song)
n = int(length_s(song) * SR)
voice = render_voice(song, shift, n)
backing = render_backing(song, shift, n)
voice *= VOICE_GAIN / max(np.abs(voice).max(), 1e-9)
backing *= BACKING_GAIN / max(np.abs(backing).max(), 1e-9)
mix = reverb(voice + backing)
mix *= 0.9 / np.abs(mix).max()
path = SONGS / f"{song_id}.wav"
sf.write(path, mix.astype(np.float32), SR, subtype="PCM_16")
print(f"{path} {len(mix) / SR:.1f} s, transposed {shift:+d}")
return path
if __name__ == "__main__":
ids = sys.argv[1:] or sorted(p.stem for p in SONGS.glob("*.json"))
for i in ids:
render(i)
+34
View File
@@ -0,0 +1,34 @@
{
"ready": [
-284.35,
-75.43,
-52.45,
-136.99,
26.46,
-278.46
],
"carry": [
-280.6,
-86.13,
-2.58,
-173.3,
85.86,
119.9
],
"give": [
-270.97,
-86.67,
-3.28,
-168.9,
56.87,
128.14
],
"look": [
-239.15,
-88.4,
-29.48,
199.97,
81.4,
158.35
]
}
+1
View File
@@ -0,0 +1 @@
{"arm_yaw_in_base_deg": -95.5, "objects": ["cup", "cup"], "waist_deg": -20.31, "measured": "2026-10-19 15:55 (median of -96.4, -94.9, -95.5; one run that paired both cups with one was left out)", "arm_xy_in_base_m": [0.114, -0.104], "arm_xy_measured": "2026-10-16 (median of 4; the depth-only 0.005, -0.120 dropped)", "arm_xy_samples": [[0.111, -0.086], [0.093, -0.095], [0.187, -0.113], [0.117, -0.129]]}
+35
View File
@@ -0,0 +1,35 @@
{
"joints": [
-297.606897,
-78.356094,
-28.782753,
-143.133593,
40.177249,
-277.868113
],
"flange": [
51.754108,
468.431956,
-181.97017,
83.715142,
46.657319,
-138.490175
],
"note": "fingers around the cup, 2026-10-13 ~18:40; cup position measured after lifting",
"cup": {
"x": -128.0,
"y": 628.0,
"top": -261.0,
"width": 76.5
},
"grasp_base": [
-128.0,
628.0,
-301.0
],
"tcp_offset_flange": [
106.4,
-86.5,
230.5
]
}
+1
View File
@@ -0,0 +1 @@
[{"body": [7.152557373046875e-06, -20.313034057617188, 0.0, -5.000152587890625], "T_cam_marker": [[-0.13049541877300497, -0.4328224408258203, -0.8919841256417281, 105.7351819926775], [-0.4646166703827714, 0.8214697601000992, -0.33063391060735514, 44.63761588420917], [0.8758437619128688, 0.3712844838646842, -0.30829456167705843, 248.5378409008255], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, -1.99951171875], "T_cam_marker": [[-0.13109959677597327, -0.42359912048709913, -0.8963128253281514, 105.37381194342754], [-0.4206983961707192, 0.8424423583913667, -0.3366061975771941, 60.99277870285539], [0.8976779796700831, 0.3329484313081354, -0.28865132410035793, 247.95504278822762], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, 0.999755859375], "T_cam_marker": [[-0.12516531610772458, -0.4289301023127997, -0.894624284810995, 105.51875264841117], [-0.370266853567398, 0.8567616751996066, -0.35897338210299606, 77.48098620434045], [0.9204542904419274, 0.28631870221677, -0.2660554452890449, 247.20187262301286], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, 3.9997100830078125], "T_cam_marker": [[-0.13449617368793312, -0.4221828372237855, -0.8964777918147111, 105.2421252158032], [-0.3158787723648555, 0.8757666797099366, -0.3650387977723803, 93.73184163095779], [0.9392184945115682, 0.23408198278275888, -0.2511458638001331, 245.38295966844217], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, 7.0003509521484375], "T_cam_marker": null}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, 10.000991821289062], "T_cam_marker": null}, {"body": [9.5367431640625e-06, -20.313034057617188, 0.0, 13.000259399414062], "T_cam_marker": null}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, 3.9990234375], "T_cam_marker": [[-0.14424547831142515, -0.420600357818681, -0.8957056330008796, 105.78419064232367], [-0.3145187107600882, 0.8777201041336978, -0.3615043559645486, 94.38888307544458], [0.9382277029423723, 0.22957081217421535, -0.25889383853068226, 246.71820224195812], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0, -5.0008392333984375], "T_cam_marker": [[-0.13290097220571792, -0.4283481218239463, -0.8937870093689394, 105.63844465753728], [-0.46625587610197694, 0.8227907664143032, -0.32499355794190965, 44.59291584053284], [0.8746100785991164, 0.3735414852908056, -0.3090695215960094, 248.08861307109524], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.312347412109375, -20.0006103515625, -5.000152587890625], "T_cam_marker": [[-0.43555552049235613, -0.4878188163103918, -0.7565211107577632, -6.765527675323052], [-0.45221763606640963, 0.8452556137757605, -0.28467904210017103, 43.8012197058485], [0.7783255091535549, 0.21811865998600505, -0.5887560207477867, 254.1215669794407], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, -19.999923706054688, -0.9990692138671875], "T_cam_marker": [[-0.4330373033529156, -0.49345739109787407, -0.7543066333234223, -6.679233361165335], [-0.39796141004587277, 0.8555270602231879, -0.3312101528337729, 66.47740358124996], [0.808767834436519, 0.15675857997810025, -0.5668521302633637, 255.52533093915892], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, -19.999923706054688, 3.000640869140625], "T_cam_marker": [[-0.4309031103457666, -0.4898192413429136, -0.7578915623653537, -6.628707719732298], [-0.33899774940938354, 0.8662140166826613, -0.36708827711854614, 88.86789346149455], [0.8363031958504747, 0.09874405355636642, -0.5393019344463176, 253.31983117198408], [0.0, 0.0, 0.0, 1.0]]}, {"body": [2.384185791015625e-06, -20.313034057617188, -19.999923706054688, 7.0003509521484375], "T_cam_marker": null}, {"body": [4.76837158203125e-06, -20.313034057617188, -19.999923706054688, 11.00006103515625], "T_cam_marker": null}, {"body": [9.5367431640625e-06, -20.313034057617188, -19.999923706054688, -5.0008392333984375], "T_cam_marker": [[-0.4351216489631407, -0.4876499825686898, -0.7568795446465396, -6.755291715449108], [-0.4562810477997529, 0.8441200910309015, -0.28154729147470536, 43.780848741096264], [0.7761937619063665, 0.2228424699619433, -0.5898003709382558, 254.3725459502891], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.312347412109375, 0.0006866455078125, -5.000152587890625], "T_cam_marker": [[-0.1329581985748362, -0.42667111948986947, -0.8945802776861316, 105.85205624883669], [-0.46877902142655276, 0.8223241671527975, -0.32253556887081675, 44.73770479830038], [0.8732515940449801, 0.3764767189478248, -0.3093492097746207, 248.7721937547269], [0.0, 0.0, 0.0, 1.0]]}]
+1
View File
@@ -0,0 +1 @@
[{"body": [4.76837158203125e-06, -20.313034057617188, 0.0, -5.000152587890625], "T_cam_marker": [[-0.1273896157295372, -0.4005910101808729, -0.9073581037090861, 201.04312013967137], [-0.34632936885426735, 0.8751962174842188, -0.337768484572377, 123.00851008952229], [0.9294233987119573, 0.27121656192714927, -0.2502273415578942, 306.9273452105425], [0.0, 0.0, 0.0, 1.0]]}, {"body": [4.76837158203125e-06, -20.313034057617188, -10.000991821289062, -5.000152587890625], "T_cam_marker": [[-0.28410385027149376, -0.41583171052066004, -0.8639264961710426, 134.9767168257047], [-0.33791067816113013, 0.8866670302094799, -0.3156547974040406, 119.5473630009602], [0.8972744150178347, 0.20225124490336985, -0.39241949249424335, 330.1692196043086], [0.0, 0.0, 0.0, 1.0]]}, {"body": [2.384185791015625e-06, -20.313034057617188, -20.0006103515625, -5.000152587890625], "T_cam_marker": [[-0.4337247753077172, -0.4186643238226531, -0.797874052242828, 65.7438189588543], [-0.3215445761576782, 0.8991124345548261, -0.2969948073156702, 116.90209369646219], [0.8417196117638279, 0.12773806788508146, -0.5245865812095626, 339.9842502907517], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, -30.000228881835938, -5.000152587890625], "T_cam_marker": [[-0.5813221672606207, -0.4193199372224046, -0.6973057637071515, -3.4195333761460085], [-0.30708252520145585, 0.9066722277665333, -0.2892158261796359, 118.40801360529157], [0.7535017322921772, 0.04600284387590483, -0.6558344896298283, 343.9320842739305], [0.0, 0.0, 0.0, 1.0]]}, {"body": [2.384185791015625e-06, -20.313034057617188, -9.999618530273438, -5.000152587890625], "T_cam_marker": [[-0.2772370060477794, -0.41479936004614754, -0.8666493716509401, 134.50182064872217], [-0.33429446173768473, 0.8872926133888251, -0.31774050902763445, 119.20748363927686], [0.9007701456693462, 0.20162665778843475, -0.3846554764199906, 329.123364292851], [0.0, 0.0, 0.0, 1.0]]}, {"body": [7.152557373046875e-06, -20.313034057617188, 0.0006866455078125, -5.000152587890625], "T_cam_marker": [[-0.12298114891000383, -0.4039714506907093, -0.9064671555217098, 201.16849994111575], [-0.3428515676582964, 0.8744558733387008, -0.3431905128899969, 123.11792963604991], [0.9313046974900449, 0.2685777217311498, -0.2460438331327997, 307.20044527520514], [0.0, 0.0, 0.0, 1.0]]}, {"body": [4.76837158203125e-06, -20.313034057617188, -0.0006866455078125, -5.000152587890625], "T_cam_marker": [[-0.11945658881415841, -0.3986202921307486, -0.9093030221496471, 200.23225006832357], [-0.3444580734667423, 0.875613515698834, -0.33859947836508636, 122.48000871551723], [0.9311706390412368, 0.27276882854740725, -0.24190578157706333, 305.72656789829443], [0.0, 0.0, 0.0, 1.0]]}, {"body": [4.76837158203125e-06, -20.313034057617188, 0.0006866455078125, -5.0008392333984375], "T_cam_marker": [[-0.11953654909844572, -0.399081192190234, -0.9090903230535767, 200.18768429038803], [-0.342231730395451, 0.8760995123248208, -0.33959842051273864, 122.43936503119288], [0.9319809312105966, 0.2705251310770096, -0.24130415934168337, 305.62604131388696], [0.0, 0.0, 0.0, 1.0]]}]
+1
View File
@@ -0,0 +1 @@
{"samples": [[0.31, -0.2, -5.0], [0.32, -0.5, -4.7], [0.39, -0.2, -3.0], [0.47, -0.7, -1.0], [0.53, -0.2, -1.0], [0.6, -0.2, -0.8], [0.66, 0.0, 6.9], [0.74, 0.0, 8.5], [0.8, 0.1, 8.5], [0.86, 0.4, 5.6], [0.92, 0.4, 5.3], [1.0, 0.4, 5.2], [1.07, 0.4, 5.2], [1.13, 0.4, 5.2], [1.19, 1.2, 6.1], [1.27, 1.8, 7.0], [1.33, 3.0, 7.0], [1.4, 3.0, 7.0], [1.47, 2.4, 7.2], [1.53, 1.5, 6.8], [1.6, 0.5, 6.2], [1.68, -0.7, 6.2], [1.74, -0.7, 7.2], [1.81, -0.5, 8.4], [1.86, -0.5, 8.4], [1.93, -1.7, 8.8], [1.99, -1.7, 10.0], [2.06, -1.0, 11.8], [2.13, -1.0, 15.3], [2.19, -0.9, 17.9], [2.26, -0.1, 22.2], [2.32, 0.5, 22.6], [2.41, 0.5, 22.6], [2.47, 0.4, 22.6], [2.54, 0.4, 25.2], [2.6, 0.4, 25.6], [2.66, -0.1, 25.9], [2.72, -0.4, 25.6], [2.8, -0.4, 26.0], [2.86, -0.6, 25.1], [2.93, -0.2, 26.0], [2.99, -0.2, 24.9], [3.07, 0.6, 21.4], [3.14, 0.6, 21.4], [3.19, -8.6, 21.0], [3.27, -8.6, 21.0], [3.33, -8.6, 20.6], [3.4, -10.1, 20.6], [3.47, -11.2, 21.5], [3.53, -11.5, 21.5], [3.59, -11.5, 20.5], [3.66, -0.4, -4.0], [3.73, -0.4, -5.0], [3.8, -0.4, -5.0], [3.87, -0.8, -5.0], [3.93, -0.3, -5.0], [3.99, -0.9, -4.3], [4.06, -10.8, 21.3], [4.13, -10.8, 21.3], [4.2, -10.0, 20.8], [4.26, -10.0, 20.2], [4.33, -9.6, 20.2], [4.41, -9.0, 19.8], [4.46, -9.0, 19.8], [4.54, -8.8, 19.5], [4.6, -8.8, 19.5], [4.66, -8.8, 19.5], [4.73, -9.1, 19.9], [4.79, -9.7, 19.9], [4.86, -10.1, 20.3], [4.93, -10.1, 20.3], [4.99, -10.2, 20.1], [5.06, -10.1, 19.9], [5.14, -9.7, 19.8], [5.19, -8.5, 19.6], [5.26, -8.2, 19.2], [5.32, -8.2, 19.6], [5.4, -8.1, 19.0], [5.46, -8.1, 19.5], [5.52, -8.1, 19.3], [5.6, -8.3, 19.4], [5.66, -8.3, 19.3], [5.73, -7.8, 19.1], [5.79, -7.5, 18.8], [5.86, -7.5, 18.1], [5.93, -7.5, 17.9], [5.99, -7.8, 17.9], [6.05, -7.1, 17.9], [6.13, -7.1, 18.0], [6.19, -7.1, 18.3], [6.25, -7.0, 18.3], [6.33, -7.0, 18.2], [6.4, -7.0, 18.2], [6.46, -7.0, 18.4], [6.53, -7.1, 18.4], [6.59, -7.1, 18.4], [6.67, -7.8, 18.6], [6.73, -8.4, 18.7], [6.79, -8.4, 18.7], [6.85, -7.9, 18.1], [6.93, -7.9, 18.1], [6.99, -8.1, 18.2], [7.06, -8.7, 18.2], [7.13, -8.7, 17.9], [7.2, -8.7, 17.9], [7.26, -8.5, 17.9], [7.33, -8.4, 18.1], [7.4, -8.5, 17.7], [7.47, -8.4, 17.8], [7.52, -8.2, 17.5], [7.59, -7.8, 17.1], [7.65, -7.8, 17.1], [7.73, -7.8, 16.9], [7.79, -7.9, 16.8], [7.87, -7.6, 16.7], [7.93, -7.9, 16.3], [8.0, -8.5, 15.9], [8.06, -8.5, 15.7], [8.12, -8.4, 15.5], [8.2, -8.3, 15.5], [8.26, -8.1, 15.8], [8.32, -7.9, 15.8], [8.39, -7.9, 15.4], [8.46, -8.2, 14.9], [8.52, -8.6, 14.9], [8.58, -9.1, 14.9], [8.66, -9.1, 14.6], [8.72, -9.1, 14.6], [8.8, -9.0, 14.6], [8.86, -8.7, 14.6], [8.92, -8.4, 14.5], [8.98, -7.8, 13.8], [9.07, -6.2, 12.8], [9.12, -3.7, 10.1], [9.18, -0.9, 5.1], [9.26, 2.6, 2.0], [9.33, 5.3, -2.8], [9.4, 6.4, -3.7], [9.46, 6.4, -4.0], [9.53, 5.2, -4.0], [9.61, 3.1, -0.5], [9.66, 0.0, 3.8], [9.73, -2.5, 5.5], [9.79, -3.8, 8.2], [9.87, -4.2, 8.9], [9.93, -4.3, 10.2], [9.99, -4.6, 10.2], [10.05, -4.6, 10.2], [10.12, -4.0, 10.4], [10.19, -3.8, 10.5], [10.25, -3.8, 10.5], [10.32, -4.1, 10.6], [10.4, -4.4, 11.0], [10.45, -4.4, 11.3], [10.53, -4.2, 11.3], [10.59, -4.2, 12.1], [10.66, -5.1, 12.1], [10.72, -5.8, 10.4], [10.79, -6.1, 10.4], [10.86, -5.8, 10.5], [10.92, -5.6, 10.5], [10.99, -5.1, 8.6], [11.05, -4.3, 8.6], [11.12, -3.8, 11.2], [11.18, -3.8, 11.2], [11.25, -5.4, 11.1], [11.31, -5.5, 10.0], [11.38, -5.5, 9.8], [11.45, -5.5, 10.0], [11.51, -5.6, 11.4], [11.58, -6.1, 13.3], [11.65, -7.7, 14.4], [11.71, -9.1, 16.1], [11.78, -9.3, 16.1], [11.84, -10.1, 15.8], [11.91, -10.3, 15.8], [11.99, -10.3, 15.8]]}
+1
View File
@@ -0,0 +1 @@
{"samples": [[0.32, 1.1, 4.3], [0.34, 0.1, 4.4], [0.36, -0.6, 4.4], [0.42, -0.6, 4.5], [0.51, -0.6, 4.9], [0.58, -0.6, 4.9], [0.64, -0.1, 5.1], [0.71, -0.1, 5.3], [0.77, -0.1, 5.3], [0.85, 0.1, 5.3], [0.9, 0.3, 5.5], [0.96, 0.4, 5.3], [1.03, 0.4, 4.8], [1.11, 0.4, 4.3], [1.17, 0.3, 4.3], [1.23, 0.6, 4.5], [1.31, 0.4, 4.5], [1.38, 0.4, 4.3], [1.44, 0.0, 4.3], [1.5, 0.0, 4.3], [1.57, 0.0, 4.7], [1.65, 0.3, 4.5], [1.72, 0.0, 5.0], [1.78, -0.2, 5.1], [1.84, -0.2, 5.5], [1.92, 0.3, 5.6], [1.96, 0.4, 5.8], [2.03, 0.4, 5.8], [2.1, 0.2, 5.8], [2.17, -0.2, 5.3], [2.23, -0.7, 4.5], [2.3, -0.5, 4.5], [2.36, -0.5, 5.5], [2.44, -0.5, 5.6], [2.5, -0.9, 5.7], [2.57, -1.5, 5.9], [2.64, -2.6, 5.9], [2.71, -4.6, 5.1], [2.77, -4.9, 5.1], [2.83, -4.9, 5.1], [2.91, -4.4, 5.6], [2.97, -4.3, 5.6], [3.03, -4.0, 6.1], [3.11, -2.0, 6.6], [3.17, -2.0, 6.6], [3.24, -1.8, 6.2], [3.3, -1.8, 6.2], [3.38, -0.3, 6.2], [3.44, 0.3, 6.0], [3.5, 1.7, 6.0], [3.57, 2.7, 6.6], [3.65, 4.5, 6.6], [3.7, 6.2, 4.6], [3.77, 7.4, 4.6], [3.83, 7.4, 3.5], [3.92, 6.9, -5.0], [3.97, 6.9, -5.0], [4.03, 10.4, -5.0], [4.11, 13.3, -5.0], [4.18, 14.0, -5.0], [4.24, 17.4, -5.0], [4.32, 17.4, -5.0], [4.38, 11.2, 3.9], [4.44, 11.0, 3.9], [4.5, 9.8, 2.4], [4.58, 6.7, 1.0], [4.63, 5.7, 0.1], [4.7, 5.7, -1.8], [4.77, 5.9, -1.8], [4.84, 7.2, -1.3], [4.9, 7.2, -0.2], [4.96, 8.1, -0.2], [5.04, 8.2, -0.7], [5.1, 8.2, -1.7], [5.16, 8.5, -4.0], [5.23, 9.0, -4.1], [5.31, 11.4, -4.1], [5.36, 14.3, -5.0], [5.43, 16.1, -5.0], [5.5, 18.4, -5.0], [5.57, 21.0, -5.0], [5.64, 21.0, -5.0], [5.71, 21.0, -5.0], [5.77, 26.4, -5.0], [5.84, 26.4, -5.0], [5.91, 23.1, -5.0], [5.97, 23.1, -5.0], [6.1, 24.1, -5.0], [6.83, 24.1, -5.0], [6.91, 23.0, -5.0], [6.97, 22.5, -5.0], [7.04, 21.1, -5.0], [7.1, 22.5, -5.0], [7.18, 23.4, -5.0], [7.24, 27.1, -5.0], [7.3, 27.1, -0.0], [7.36, 24.0, 5.0], [7.44, 22.0, 8.0], [7.51, 22.0, 10.1], [7.58, 23.1, 10.1], [7.65, 23.1, 7.0], [7.7, 20.6, 7.0], [7.78, 14.6, 6.6], [7.83, 12.9, 9.3], [7.9, 9.3, 9.3], [7.96, 5.4, 9.6], [8.03, 5.4, 9.9], [8.1, 9.1, 10.0], [8.18, 9.1, 9.9], [8.23, 6.2, 10.0], [8.31, 2.5, 9.5], [8.37, 1.6, 9.1], [8.44, -0.8, 8.7], [8.49, -3.4, 8.7], [8.57, -5.9, 6.1], [8.64, -10.7, 1.2], [8.7, -18.0, -1.9], [8.76, -23.2, -2.0], [8.84, -24.2, -3.4], [8.9, -27.6, -4.5], [8.96, -29.6, -4.5], [9.03, -30.7, -5.0], [9.1, -32.6, -5.0], [9.16, -32.6, -5.0], [9.23, -23.6, -0.6], [9.3, -15.5, 6.1], [9.37, -10.4, 11.0], [9.42, -5.7, 11.2], [9.5, -5.7, 11.4], [9.57, -5.8, 11.4], [9.63, -5.8, 11.5], [9.7, -6.2, 12.8], [9.77, -7.0, 13.5], [9.83, -7.0, 15.3], [9.9, -6.3, 15.3], [9.96, -5.1, 15.0], [10.03, -4.6, 14.7], [10.1, -4.1, 14.7], [10.17, -4.1, 14.1], [10.23, -4.4, 14.1], [10.3, -5.6, 14.1], [10.36, -6.2, 13.7], [10.43, -6.6, 11.6], [10.5, -6.6, 11.6], [10.57, -6.3, 11.6], [10.62, -6.3, 13.4], [10.7, -6.3, 15.2], [10.76, -6.3, 15.2], [10.83, -7.5, 13.6], [10.89, -9.4, 1.8], [10.97, -11.6, -0.5], [11.02, -17.5, -5.0], [11.1, -19.0, -5.0], [11.15, -22.7, -5.0], [11.22, -24.0, -5.0], [11.29, -24.1, -5.0], [11.42, -24.7, -5.0], [11.76, -31.9, -5.0], [12.03, -31.9, -5.0], [12.09, -23.6, -5.0], [12.17, -18.9, -5.0], [12.22, -15.5, -5.0], [12.29, -13.0, -5.0], [12.36, -12.1, -5.0], [12.42, -11.3, -5.0], [12.49, -11.3, -5.0], [12.55, -12.1, -5.0], [12.63, -12.3, -5.0], [12.7, -13.9, -5.0], [12.75, -14.5, -5.0], [12.83, -16.0, -5.0], [12.89, -16.0, -5.0], [12.96, -17.4, -5.0], [13.02, -21.4, -5.0], [13.1, -22.0, -5.0], [13.15, -24.2, -5.0], [13.23, -24.2, -5.0], [13.28, -23.0, -5.0], [13.35, -22.8, -5.0], [13.42, -21.7, -5.0], [13.49, -21.6, -5.0], [13.54, -21.7, -5.0], [13.68, -25.0, -5.0], [13.75, -25.0, -5.0], [13.82, -27.2, -5.0], [14.29, -27.7, -5.0], [14.36, -32.8, -5.0], [14.42, -32.8, -5.0], [14.5, -26.3, -5.0], [14.57, -25.8, -5.0], [14.63, -25.8, -5.0], [14.69, -31.1, -5.0], [14.75, -31.6, -5.0], [14.84, -31.6, -5.0], [14.9, -29.9, -5.0], [14.96, -29.8, -5.0]]}
+1
View File
@@ -0,0 +1 @@
{"samples": [[0.35, -15.9, 1.1], [0.37, -11.6, 2.4], [0.4, -7.3, 2.0], [0.48, -1.2, 2.0], [0.54, 0.6, 2.0], [0.61, 2.3, 3.0], [0.68, 2.3, 5.0], [0.74, -0.0, 27.5], [0.8, -0.2, 28.0], [0.86, -0.0, 27.5], [0.93, 0.6, 26.5], [1.0, 0.7, 23.2], [1.07, 0.7, 18.9], [1.13, 0.3, 10.0], [1.2, -0.1, -3.6], [1.27, -1.4, -5.0], [1.33, -1.4, -4.0], [1.41, -2.9, -4.0], [1.47, -4.0, -4.0], [1.54, -4.7, -3.7], [1.6, -4.7, -3.7], [1.67, -2.8, -3.6], [1.73, -1.3, -3.6], [1.81, -1.3, -5.0], [1.88, -1.3, -5.0], [1.94, -1.6, -5.0], [2.01, -1.6, -5.0], [2.08, -1.7, -5.0], [2.16, -1.6, -5.0], [2.22, -1.6, -5.0], [2.28, -1.3, -5.0], [2.35, -0.9, -5.0], [2.41, -0.9, -5.0], [2.48, -1.5, -5.0], [2.55, -1.9, -5.0], [2.62, -1.9, -5.0], [2.68, -1.9, -5.0], [2.75, -1.9, -5.0], [2.82, -1.8, -5.0], [2.88, -1.9, -5.0], [2.95, -2.2, -5.0], [3.02, -2.8, -5.0], [3.07, -2.2, -4.8], [3.15, 1.3, -1.6], [3.21, 1.3, -1.6], [3.28, 1.4, -2.1], [3.34, 0.2, -3.1], [3.42, -1.8, -5.0], [3.49, -1.8, -5.0], [3.55, -1.3, -5.0], [3.62, -1.3, -5.0], [3.67, -2.4, -1.5], [3.73, -2.4, -0.9], [3.81, -1.0, -0.4], [3.86, -1.0, -0.4], [3.93, -1.0, -1.6], [4.0, -1.0, -3.3], [4.06, -1.0, -5.0], [4.13, -1.3, -5.0], [4.21, -1.3, -5.0], [4.28, -1.5, -3.4], [4.34, -2.3, -3.4], [4.41, -2.3, 1.4], [4.48, -1.7, 2.1], [4.54, 1.7, 2.1], [4.62, 2.2, 2.1], [4.68, 1.7, 2.2], [4.75, -2.5, 5.5], [4.81, -3.6, 5.5], [4.88, -2.5, 5.3], [4.94, 2.2, -0.1], [5.0, 2.4, -0.1], [5.08, 3.1, 0.0], [5.15, 2.8, 0.0], [5.21, 2.8, -0.5], [5.28, 2.2, -0.8], [5.35, 1.7, -0.5], [5.42, 1.3, -1.3], [5.48, -0.9, -0.3], [5.54, -2.4, -0.3], [5.61, -2.7, -0.1], [5.68, -2.7, 0.1], [5.73, -2.8, 1.4], [5.82, -3.1, 1.4], [5.87, -3.3, -0.9], [5.94, -4.4, -0.9], [6.01, -3.3, 2.2], [6.08, -2.4, 2.2], [6.15, -1.0, 0.2], [6.22, -0.3, 0.2], [6.28, 0.7, 0.6], [6.35, 0.9, 0.6], [6.41, 1.2, 0.5], [6.48, 1.4, 0.5], [6.54, 1.4, 0.6], [6.62, 0.6, 0.6], [6.67, 0.6, 0.6], [6.74, 0.6, 0.9], [6.79, 0.9, 1.1], [6.87, 1.4, 1.1], [6.94, 1.4, 0.8], [7.01, 1.0, 0.8], [7.07, 1.0, 1.4], [7.14, -3.0, 3.9], [7.2, -3.0, 2.8], [7.28, -3.3, 4.6], [7.34, -3.3, 2.8], [7.4, 1.2, 2.3], [7.49, 1.2, 1.8], [7.56, 1.2, 1.8], [7.61, 1.4, 2.0], [7.66, -2.9, 8.2], [7.73, -1.3, 15.6], [7.81, -1.3, 20.4], [7.88, -0.5, 22.7], [7.95, 0.6, 24.6], [8.01, 0.6, 28.3], [8.08, 0.9, 28.8], [8.16, 0.9, 31.6], [8.22, 0.9, 33.3], [8.28, 0.9, 33.3], [8.35, 1.8, 33.1], [8.41, 1.8, 32.9], [8.48, 1.8, 32.9], [8.54, 1.6, 33.6], [8.61, 1.6, 34.6], [8.67, 1.6, 34.7], [8.74, 1.7, 34.7], [8.8, 1.7, 34.1], [8.88, 1.5, 30.7], [8.95, 1.3, 30.7], [9.02, 1.5, 30.8], [9.08, 1.3, 31.6], [9.15, 1.5, 32.6], [9.21, 1.8, 33.4], [9.28, 1.8, 33.8], [9.35, 1.3, 33.8], [9.4, 1.3, 33.8], [9.48, 2.3, 32.6], [9.54, 2.3, 29.9], [9.6, 2.1, 25.0], [9.67, 1.5, 22.6], [9.74, 1.4, 22.6], [9.81, 1.5, 23.6], [9.88, 1.4, 23.9], [9.94, 0.6, 23.9], [10.0, 0.6, 22.6], [10.07, 0.6, 22.2], [10.14, 0.1, 18.7], [10.21, -0.0, 15.8], [10.26, -0.0, 15.8], [10.33, -0.4, 15.3], [10.4, -0.4, 15.5], [10.47, -0.3, 15.3], [10.52, -0.1, 15.3], [10.59, -0.3, 14.9], [10.67, 0.1, 12.7], [10.74, 0.2, 11.2], [10.8, 0.2, 11.2], [10.87, -0.0, 11.1], [10.94, -0.2, 6.8], [11.01, -0.6, 6.8], [11.06, -0.8, 8.6], [11.13, -1.1, 8.6], [11.2, -0.8, 8.6], [11.27, -0.5, 9.6], [11.34, -0.5, 10.6], [11.4, -0.6, 10.9], [11.47, -0.6, 10.6], [11.53, -0.6, 10.6], [11.6, -0.5, 10.6], [11.66, -0.7, 12.4], [11.72, -1.0, 12.4], [11.79, -1.0, 9.7], [11.87, -1.0, 9.7], [11.95, -0.4, 13.0], [12.0, -0.3, 16.9], [12.07, 0.2, 17.5], [12.13, 0.2, 19.2], [12.21, -0.2, 20.6], [12.26, -1.0, 21.4], [12.34, -1.2, 23.4], [12.4, -1.2, 25.5], [12.48, -0.9, 31.6], [12.54, 0.3, 35.0], [12.61, 1.2, 35.0], [12.66, 1.4, 35.0], [12.73, 3.1, 35.0], [12.81, 3.7, 35.0], [12.88, 4.2, 35.0], [12.95, 4.3, 15.2], [13.01, 4.6, 9.8], [13.08, 5.4, 9.8], [13.15, 6.9, 17.6], [13.21, 9.6, 33.9], [13.28, 9.8, 35.0], [13.35, 10.1, 35.0], [13.41, 11.6, 35.0], [13.48, 12.6, 26.2], [13.55, 12.6, 14.7], [13.6, 13.1, 3.5], [13.69, 13.1, 3.5], [13.74, 13.1, 4.0], [13.81, 13.6, 12.2], [13.88, 13.6, 24.9], [13.94, 13.9, 27.8], [14.0, 13.9, 32.8], [14.07, 12.4, 33.4], [14.13, 12.4, 33.4], [14.21, 12.3, 26.4], [14.27, 9.9, 23.2], [14.35, 9.8, 23.2], [14.41, 7.2, 23.2], [14.48, 6.5, 23.8], [14.54, 5.0, 31.5], [14.62, 2.9, 35.0], [14.68, 2.9, 35.0], [14.75, 6.3, 10.8], [14.8, 6.3, 8.8], [14.88, 6.3, 8.2], [14.94, 7.9, 5.1], [15.02, 9.3, 4.9]]}
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
[
{
"name": "chair",
"colour": "yellow",
"map": [
-1.472,
8.203
],
"taught": "2026-10-16 16:05"
}
]
+9
View File
@@ -0,0 +1,9 @@
{
"title": "Arirang", "title_ko": "아리랑", "lang": "ko",
"source": "Korean traditional folk song (UNESCO intangible heritage); the standard melody as in John Chambers' abc collection; public domain",
"names": ["arirang", "아리랑"],
"lyrics": "아리랑 아리랑 아라리요 아리랑 고개로 넘어간다 나를 버리고 가시는 님은 십리도 못 가서 발병 난다",
"bpm": 88, "meter": 3, "intro_bars": 1,
"melody": "아:D4:1.5 리:E4:.5 랑:D4:.5 ~:E4:.5 | 아:G4:1.5 리:A4:.5 랑:G4:.5 ~:A4:.5 | 아:B4:1 라:A4:.333 리:B4:.333 ~:A4:.334 요:G4:.5 ~:E4:.5 | ~:D4:1.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 아:G4:1.5 리:A4:.5 랑:G4:.5 ~:A4:.5 | 고:B4:.5 개:A4:.5 로:G4:.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 넘:G4:1.5 어:A4:.5 간:G4:1 | 다:G4:3 | 나:D5:2 를:D5:1 | 버:D5:1 리:B4:1 고:A4:1 | 가:B4:1 시:A4:.333 는:B4:.333 ~:A4:.334 님:G4:.5 은:E4:.5 | ~:D4:1.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 십:G4:1.5 리:A4:.5 도:G4:.5 ~:A4:.5 | 못:B4:.5 가:A4:.5 서:G4:.5 ~:E4:.5 ~:D4:.5 ~:E4:.5 | 발:G4:1.5 병:A4:.5 난:G4:1 | 다:G4:3",
"chords": "G G G D G Em C G Bm D G D G Em C G"
}
+9
View File
@@ -0,0 +1,9 @@
{
"title": "Happy Birthday", "title_ko": "생일 축하 노래", "lang": "en",
"source": "Hill sisters' melody (1893) with the 'Happy Birthday' words; public domain (US court ruling 2015, EU since 2017)",
"names": ["happy birthday", "birthday", "생일 축하", "생일"],
"lyrics": "Happy birthday to you, happy birthday to you, happy birthday dear friend, happy birthday to you.",
"bpm": 100, "meter": 3, "intro_bars": 1, "repeat": 2,
"melody": "-:r:2 Hap:G4:.75 pee:G4:.25 | birth:A4:1 day:G4:1 to:C5:1 | you:B4:2 Hap:G4:.75 pee:G4:.25 | birth:A4:1 day:G4:1 to:D5:1 | you:C5:2 Hap:G4:.75 pee:G4:.25 | birth:G5:1 day:E5:1 dear:C5:1 | friend:B4:1 ~:A4:1 Hap:F5:.75 pee:F5:.25 | birth:E5:1 day:C5:1 to:D5:1 | you:C5:3",
"chords": "C C G7 G7 C C7 F C,G7 C"
}
+9
View File
@@ -0,0 +1,9 @@
{
"title": "Row, Row, Row Your Boat", "title_ko": "노를 저어라", "lang": "en",
"source": "American nursery rhyme, first published 1852 (melody 1881); public domain",
"names": ["row row", "row your boat", "boat song"],
"lyrics": "Row, row, row your boat, gently down the stream. Merrily, merrily, merrily, merrily, life is but a dream.",
"bpm": 200, "meter": 6, "intro_bars": 1, "repeat": 3,
"melody": "Row:C4:3 row:C4:3 | row:C4:2 your:D4:1 boat:E4:3 | jent:E4:2 lee:D4:1 down:E4:2 the:F4:1 | stream:G4:6 | mer:C5:1 rih:C5:1 lee:C5:1 mer:G4:1 rih:G4:1 lee:G4:1 | mer:E4:1 rih:E4:1 lee:E4:1 mer:C4:1 rih:C4:1 lee:C4:1 | life:G4:2 is:F4:1 but:E4:2 uh:D4:1 | dream:C4:6",
"chords": "C C C C C C G7 C"
}
+9
View File
@@ -0,0 +1,9 @@
{
"title": "Three Bears", "title_ko": "곰 세 마리", "lang": "ko",
"source": "Korean children's song, words and melody by unknown authors (traditional); no registered author",
"names": ["three bears", "three bear", "곰 세 마리", "곰세마리", "곰 세마리"],
"lyrics": "곰 세 마리가 한 집에 있어 아빠 곰 엄마 곰 애기 곰 아빠 곰은 뚱뚱해 엄마 곰은 날씬해 애기 곰은 너무 귀여워 으쓱 으쓱 잘한다",
"bpm": 108, "meter": 4, "intro_bars": 1, "repeat": 2,
"melody": "곰:C4:1 세:C4:.5 마:C4:.5 리:C4:1 가:C4:1 | 한:E4:1 집:G4:.5 에:G4:.5 이:E4:1 써:C4:1 | 아:G4:.5 빠:G4:.5 곰:E4:1 엄:G4:.5 마:G4:.5 곰:E4:1 | 애:C4:.5 기:C4:.5 곰:C4:2 -:r:1 | 아:G4:.5 빠:G4:.5 곰:E4:.5 은:C4:.5 뚱:G4:.5 뚱:G4:.5 해:G4:1 | 엄:G4:.5 마:G4:.5 곰:E4:.5 은:C4:.5 날:G4:.5 씬:G4:.5 해:G4:1 | 애:G4:.5 기:G4:.5 곰:E4:.5 은:C4:.5 너:G4:.5 무:G4:.5 귀:G4:.5 여:A4:.5 | 워:G4:2 으:C5:.5 쓱:G4:.5 으:C5:.5 쓱:G4:.5 | 잘:E4:1 한:D4:1 다:C4:1 -:r:1",
"chords": "C C C C C,C,G,G C,C,G,G C,C,G,G C C,G,C,C"
}
+9
View File
@@ -0,0 +1,9 @@
{
"title": "Twinkle, Twinkle, Little Star", "title_ko": "반짝반짝 작은 별", "lang": "en",
"source": "French melody 'Ah! vous dirai-je, maman' (1761), words by Jane Taylor (1806); public domain",
"names": ["twinkle", "little star", "반짝반짝", "작은 별"],
"lyrics": "Twinkle, twinkle, little star, how I wonder what you are. Up above the world so high, like a diamond in the sky. Twinkle, twinkle, little star, how I wonder what you are.",
"bpm": 104, "meter": 4, "intro_bars": 1,
"melody": "Twin:C4:1 kle:C4:1 twin:G4:1 kle:G4:1 | lit:A4:1 tle:A4:1 star:G4:2 | how:F4:1 I:F4:1 won:E4:1 der:E4:1 | what:D4:1 you:D4:1 are:C4:2 | up:G4:1 uh:G4:1 buv:F4:1 the:F4:1 | world:E4:1 so:E4:1 high:D4:2 | like:G4:1 uh:G4:1 dye:F4:1 mund:F4:1 | in:E4:1 the:E4:1 sky:D4:2 | Twin:C4:1 kle:C4:1 twin:G4:1 kle:G4:1 | lit:A4:1 tle:A4:1 star:G4:2 | how:F4:1 I:F4:1 won:E4:1 der:E4:1 | what:D4:1 you:D4:1 are:C4:2",
"chords": "C F,C F,C G,C C,F C,G C,F C,G C F,C F,C G,C"
}
+169
View File
@@ -0,0 +1,169 @@
# 00. Start here
The path from zero to working on the real Lumi: what the robot is, what to install, how to power it on and connect, the first slow motions, and where each part is documented. Passwords are not in these docs; ask the project owner.
---
## 0. The robot and its control channels
Lumi is a JAKA mobile manipulator: mobile base, lift, waist, 2-joint head, 6-joint arm with a gripper, two RGB-D cameras and a microphone array ([01_HARDWARE.md](01_HARDWARE.md)).
| Channel | Controls | Address |
|---|---|---|
| Body HTTP API | lift, waist, head yaw, head pitch | `http://192.168.10.90:5000/api/extaxis/...` |
| Arm controller | 6-joint arm, tool I/O (gripper) | `192.168.10.90` (JAKA SDK `jkrc`, or JSON commands on TCP port 10001) |
| AGV TCP API | base driving, navigation, people detection | `192.168.10.10:31001` |
| USB 3.0 (to the onboard computer) | head and torso cameras, microphone array | — |
---
## 1. Read first
1. [11_SAFETY.md](11_SAFETY.md): stop devices and operating rules.
2. [01_HARDWARE.md](01_HARDWARE.md): what is on the robot.
3. [02_NETWORK_AND_ACCESS.md](02_NETWORK_AND_ACCESS.md): addresses and how to connect.
---
## 2. Prepare your computer
| Need | macOS (Apple Silicon) | Ubuntu 22.04 / Jetson |
|---|---|---|
| Python 3.10+ with `requests`, `numpy`, `opencv-python`, `pyserial`, `pyaudio` | `pip install requests numpy opencv-python pyserial pyaudio` (pyaudio needs `brew install portaudio`) | `pip install ...`, `sudo apt install portaudio19-dev` |
| JAKA SDK `jkrc` (arm) | no macOS build: use Docker Desktop with an `arm64v8/python:3.10` container and the `aarch64-linux-gnu` files ([04_ARM.md](04_ARM.md)) | native: `x86_64-linux-gnu` or `aarch64-linux-gnu` files + `LD_LIBRARY_PATH` |
| Orbbec camera tools | OrbbecViewer macOS arm64 build | OrbbecSDK `.deb` (amd64 / arm64) + pyorbbecsdk ([06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md)) |
| Browser | Chrome | Chrome |
| JAKA App 1.7.2 (optional) | iPad / Android tablet / Windows PC | Windows PC / tablet |
Download the SDK:
```bash
curl -L -o jaka_sdk.zip "https://www.jaka.com/prod-api/common/download/resource?resource=%2Fprofile%2Fupload%2F2025%2F04%2F25%2F20250425134342A024.zip"
unzip jaka_sdk.zip && tar -xf "SDK V2.2.7.7z" # macOS tar (bsdtar) reads .7z; on Linux use 7z x
ls "SDK V2.2.7/Linux/python3/" # aarch64-linux-gnu, x86_64-linux-gnu, i686-linux-gnu
```
Keep the SDK binaries out of git (they are large).
---
## 3. Power on and off
1. Robot on a flat floor, free space around, E-stop on the column released, manual charging cable unplugged.
2. **Base:** main switch underneath (next to the rear right caster) to **I**. Hold the power button: two short beeps → release after the third, long beep. LED flashes green, then **white** = ready.
3. Wait about **5 minutes** for the controller and the onboard computer to start.
4. **Arm:** in Cobo π (`https://192.168.10.90`) or the JAKA App: **Power** → ring light blue → **Enable** → green.
5. **Body:** open `http://192.168.10.90:5000` → Reset → Enable (or through the API, [03_BODY_LIFT_WAIST_HEAD.md](03_BODY_LIFT_WAIST_HEAD.md)).
Power off in reverse: body Disable → arm Disable → arm Power off → hold the base button (seven short beeps, release on the eighth) → main switch to O if the robot is stored for more than 30 days.
---
## 4. Connect
1. Join the robot Wi-Fi `Lumi<serial>` **or** plug a cable into the base's RJ45 port.
2. Your IP must be `192.168.10.x`. If it is `10.5.5.x`, set a static address such as `192.168.10.150/24`, gateway `192.168.10.9` ([02 §2](02_NETWORK_AND_ACCESS.md#fix-a-1055x-address)).
3. Check:
```bash
ping -c 2 192.168.10.90
ping -c 2 192.168.10.10
curl -s http://192.168.10.90:5000/api/extaxis/status
```
4. Web pages: `https://192.168.10.90` (Cobo π, log in as Administrator), `http://192.168.10.90:5000` (body), `http://192.168.10.10:9001` (AGV).
---
## 4a. The onboard computer
The cameras and the microphone array are USB devices: they work only on the computer plugged into the base's USB 3.0 port. On Lumi this is the onboard **Jetson AGX Thor** ([08_NVIDIA_THOR.md](08_NVIDIA_THOR.md)), which runs the robot software. Body, arm and base are network devices and can be reached from any computer on the robot network.
```
Laptop ──Wi-Fi "Lumi<serial>"──> robot network 192.168.10.x
│ ├─ 192.168.10.90 arm + body controller (MiniCab)
│ ├─ 192.168.10.10 AGV base computer
└──SSH──> onboard computer (Thor) ─┘
└─USB 3.0─> head camera, torso camera, microphone array
```
Neither `192.168.10.90` (arm controller) nor `192.168.10.10` (AGV navigation PC) runs user code; the onboard computer does.
1. Find the onboard computer's IP: router page `http://192.168.10.79` → connected devices, or `nmap -sn 192.168.10.0/24`.
2. `ssh <user>@<ip>`.
3. Check the USB devices: `lsusb | grep -i -E "2bc5|orbbec"` (two Gemini 2 L) and `arecord -l` (AIUI-USB-MC).
4. Edit code remotely (VS Code Remote-SSH), or keep it in git and pull / rsync it there.
5. Camera images on a laptop: OrbbecViewer over X11 forwarding (`ssh -X`), or frames published over the network (ROS 2 `OrbbecSDK_ROS2`, or an HTTP / MJPEG server).
The software that runs on the onboard computer is described in [../README.md](../README.md).
---
## 5. Read-only checks
| Part | Check | Doc |
|---|---|---|
| Arm | Cobo π: controller version, arm model (`MiniCobo2`), joint limits, joint speed limits, mounting, payload | [04_ARM.md](04_ARM.md) |
| Arm SDK | `login()` (or `login(1)`), `get_sdk_version()`, `get_robot_status_simple()`, `get_joint_position()` | [04_ARM.md](04_ARM.md) |
| Body | `GET /sysinfo`, `GET /status` | [03 §2](03_BODY_LIFT_WAIST_HEAD.md#2-http-api) |
| Base | web monitor: map, position, battery, E-stops; API `robot_status`, `get_power_status`, `software/get_version`, `markers/query_brief` | [05_AGV_BASE.md](05_AGV_BASE.md) |
| Cameras | `lsusb` / OrbbecViewer: two Gemini 2 L, serial numbers, head / torso | [06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md) |
| Microphone | `AIUI-USB-MC` in the audio device list; record 5 s | [07_VOICE_AND_AUDIO.md](07_VOICE_AND_AUDIO.md) |
---
## 6. First motions (slow)
1. **Body** ([03 §5](03_BODY_LIFT_WAIST_HEAD.md#5-bring-up-sequence)): enable, `moveto` with `vel=10`: head pitch 0→20→0, head yaw ±30, waist ±20, lift 0→50→0.
2. **Arm** ([04_ARM.md](04_ARM.md)): collision level 1; each joint +5° and back at 0.2 rad/s; then the factory pose `[0, 120, -120, 0, -90, 0]°`.
3. **Base** ([05_AGV_BASE.md](05_AGV_BASE.md)): open area, `joy_control` 0.1 m/s for 2 s at 10 Hz, 0.3 rad/s turn; soft E-stop.
---
## 7. Development areas
| Area | Approach | Docs |
|---|---|---|
| Arm trajectories | `joint_move` sequences → `servo_j` streaming (8 ms) where the controller supports servo mode → MoveIt 2 through the vendor ROS servers | [04_ARM.md](04_ARM.md), [09_ROS2_TELEOP_AND_SIM.md](09_ROS2_TELEOP_AND_SIM.md) |
| Base | `joy_control` at 10 Hz (v, w) → markers + `/api/move` navigation | [05_AGV_BASE.md](05_AGV_BASE.md) |
| Cameras / vision | pyorbbecsdk colour + depth, intrinsics, hand-eye calibration | [06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md) |
| Sound direction | mic array direction output → head / waist turn; AGV `human_detection` as a second source | [07_VOICE_AND_AUDIO.md](07_VOICE_AND_AUDIO.md) |
| Onboard computer | Jetson AGX Thor setup, Docker, voice services | [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md) |
| Gripper | tool I/O signals, gripper control | [10_GRIPPER.md](10_GRIPPER.md) |
| Tunable values | speeds, distances, thresholds with file and line | [TUNING.md](TUNING.md) |
---
## 8. Coordinate frames and units
| Interface | Units | Frame |
|---|---|---|
| Body HTTP API | mm, degrees | joint space |
| Arm SDK joints | rad | SDK joint space = URDF `l_a1…l_a6` |
| Arm SDK Cartesian | mm, rad (RX, RY, RZ) | arm base / user frame; TCP = active tool (default flange centre). Cobo π shows degrees and a "World" frame that includes the mounting angle |
| AGV `joy_control` | m/s, rad/s | base: + forward, + left turn |
| AGV poses, markers | m, rad | map frame made during mapping |
| AGV `human_detection` | m | robot: x ahead, right-handed (y left) |
| Camera depth | mm (after `depth_scale`) | camera optical frame |
| URDF | m, rad | robot front = −y of `base_link`; arm base on the waist link at (−0.104, 0, 0.069) |
---
## 9. Documentation map
| Doc | Content |
|---|---|
| [README.md](README.md) | index |
| [01_HARDWARE.md](01_HARDWARE.md) | specs of every part, connectors, lights, model files |
| [02_NETWORK_AND_ACCESS.md](02_NETWORK_AND_ACCESS.md) | network map, addresses, static IP, apps and tools |
| [03_BODY_LIFT_WAIST_HEAD.md](03_BODY_LIFT_WAIST_HEAD.md) | body web page, HTTP API, Cobo π external axes, ROS node |
| [04_ARM.md](04_ARM.md) | Cobo π, controller versions, Python SDK, joint space, trajectories, settings, tool I/O |
| [05_AGV_BASE.md](05_AGV_BASE.md) | web monitor (mapping, markers, correction) and TCP API |
| [06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md) | Orbbec tools, Python, intrinsics, hand-eye calibration |
| [07_VOICE_AND_AUDIO.md](07_VOICE_AND_AUDIO.md) | mic array, recording, sound direction |
| [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md) | Jetson Thor setup, Docker, voice services |
| [09_ROS2_TELEOP_AND_SIM.md](09_ROS2_TELEOP_AND_SIM.md) | ROS 2 / MoveIt / Isaac Sim, VR teleop, ACT |
| [10_GRIPPER.md](10_GRIPPER.md) | gripper hardware, signals, control |
| [11_SAFETY.md](11_SAFETY.md) | stop devices and rules |
| [12_SOURCES.md](12_SOURCES.md) | sources and download links |
| [TUNING.md](TUNING.md) | tunable values |
+239
View File
@@ -0,0 +1,239 @@
# 01. Hardware
What the JAKA Lumi is made of, with its specifications from the vendor material ([12_SOURCES.md](12_SOURCES.md)). Where two vendor sources disagree, both values are given.
---
## 1. The robot at a glance
Lumi is a wheeled mobile manipulator ("embodied AI platform"): an AGV base, a lifting column, a waist joint, a 2-joint head, a 6-joint arm on the side of the column, two RGB-D cameras and a microphone array.
| Part | What it is | Controlled through | Detail doc |
|---|---|---|---|
| Mobile base (AGV) | Differential-drive base with 2D lidar SLAM ("WATER" platform) | TCP commands to `192.168.10.10:31001`; web UI `:9001` | [05_AGV_BASE.md](05_AGV_BASE.md) |
| Lift, waist, head (4 joints) | Lifting column, waist turn, head yaw, head pitch | HTTP `192.168.10.90:5000/api/extaxis/...`; also external axes in Cobo π | [03_BODY_LIFT_WAIST_HEAD.md](03_BODY_LIFT_WAIST_HEAD.md) |
| Arm (6 joints) | JAKA Mini 2 ("MiniCobo2") with a MiniCab controller inside the base | JAKA SDK `jkrc`; Cobo π web UI `https://192.168.10.90`; JAKA App | [04_ARM.md](04_ARM.md) |
| Head and torso cameras | Orbbec Gemini 2 L RGB-D (+ IMU) | USB 3.0 to the host computer | [06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md) |
| Base camera, lidar, ultrasonics, IMU, bumper | Built into the AGV, used by its navigation | AGV API | [05_AGV_BASE.md](05_AGV_BASE.md) |
| Voice module | iFlytek AIUI XF-USB-MC, 6-mic ring array | USB audio to the host computer | [07_VOICE_AND_AUDIO.md](07_VOICE_AND_AUDIO.md) |
| Main AI computer | Jetson AGX Thor (vendor options: Orin NX / AGX Orin / AGX Thor) | Ethernet / Wi-Fi to the robot network; USB 3.0 to the base | [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md) |
| Gripper | Zimmer GEP2013IO-05-B electric parallel gripper on the arm flange | Arm tool I/O (digital outputs, analog input) | [10_GRIPPER.md](10_GRIPPER.md) |
Camera positions: **1** head (front of the head), **2** torso (under the handle on the column), **3** base front (the AGV's own camera).
### Whole robot
| Item | Value | Source |
|---|---|---|
| Size (W × D × H) | 510 × 510 × 1460–1860 mm (height changes with the lift) | Lumi manual 5.1.1, brochure |
| Weight | 95.6 kg | Brochure |
| Degrees of freedom | 12 = lift 1 + waist 1 + head 2 + arm 6 + 2 drive wheels | Lumi manual 5.1.1 |
| Power | 800 W (manual) / 1500 W (brochure) | |
| Arm and controller supply | 48 V DC; base battery 24 V | Lumi manual, AGV spec |
| Arm payload | 2 kg | Lumi manual, brochure, web doc 3.3.5 |
| Lift range | 0–400 mm (hardware); 0–300 mm (body API doc) | see [03](03_BODY_LIFT_WAIST_HEAD.md#joint-ranges) |
| Waist | ±160° (hardware); ±140° (body API doc) | |
| Head yaw (neck) | ±180° | |
| Head pitch | −5…+35° | |
| End-effector options (vendor) | 3-finger or 5-finger dexterous hands, electric grippers, soft grippers | Brochure |
| Simulation support (vendor claim) | "natively compatible with MuJoCo and NVIDIA Isaac Sim" | Brochure |
---
## 2. Arm: JAKA Mini 2
From the Lumi manual 5.1.2, Mini hardware manual 3.3 and web doc 3.3.5.
| Item | Value |
|---|---|
| Model | JAKA Mini 2; Cobo π shows it as `MiniCobo2`. (MiniCobo, named in the vendor teleop list, is the 1 kg / 24 V sibling.) |
| Payload | 2 kg |
| Weight | 9.9 kg |
| Reach | 580 mm |
| Repeatability | ±0.1 mm |
| Max tool speed | 1 m/s |
| Rated power | 180 W |
| Supply | 48 V DC; under-voltage protection at ≤ 30 V |
| Communication | TCP/IP, Modbus TCP, Modbus RTU, PROFINET, EtherNet/IP |
| Tool I/O | 2 DI, 2 DO, 2 AI, 24 V supply, M8 8-pin connector (pinout in [04_ARM.md](04_ARM.md#8-tool-io-connector-m8-8-pin-tio-v3)) |
| Base diameter | 124 mm |
| IP rating | IP40 |
| Mounting | Any angle; on Lumi it hangs on the side of the column (on the waist link) |
| Max load on the arm base | Fx/Fy 120 N, Fz 140 N, Mx/My 100 Nm, Mz 90 Nm (not all at once) |
| Max flange torque | 14 Nm |
| Flange | ISO 9409-1, pitch circle 50 mm, 4 × M6 (15.3 Nm, screws grade ≥ 12.9), 1 × Ø6 H7 locating pin hole rotated 45° clockwise from +Xm |
| Flange buttons | FREE (hand-guiding / drag), POINT (record a point in the app) |
| Ring light at the arm base | blue = powered not enabled, green = enabled, red = fault / protective stop, yellow = drag mode, yellow fast flashing = paused / single step |
| Joint | Range | URDF joint | URDF limit (rad) |
|---|---|---|---|
| J1 | ±360° | `l_a1` | ±6.2831 |
| J2 | ±125° | `l_a2` | ±2.1816 |
| J3 | ±130° | `l_a3` | ±2.2689 |
| J4 | ±360° | `l_a4` | ±6.2831 |
| J5 | ±120° | `l_a5` | ±2.0943 |
| J6 | ±360° | `l_a6` | ±6.2831 |
### Arm controller: MiniCab
| Item | Value |
|---|---|
| Location | Inside the AGV base |
| Size / weight | 180 × 46.6 × 128 mm, 1.1 kg |
| Supply | 48 V DC (Mini 2) |
| I/O | 7 configurable channels (NPN, triggered by 0 V) |
| Network | Wi-Fi (DHCP only) and two LAN ports: LAN1 fixed at `10.5.5.x`, LAN2 configurable (cannot be set to `10.5.5.x`) |
| Wi-Fi reset | Hold the button next to the antenna for > 10 s (gateway goes back to factory settings) |
| Brake voltage | Must be set in the app when an external power supply is used (robot powered off and disabled) |
| Controller software | 1.7.1-46-X64-minicab (vendor teleoperation docs); controller 3.2 with Cobo π on newer robots. See [04_ARM.md](04_ARM.md#2-controller-versions-17-vs-32) |
| Absolute limits | logic/power supply −0.3…40 V absolute; recommended 40–56 V (48 V typical); average current 3.75 A, peak 12.5 A |
| Typical power | off 1 W, on 12 W, with arm power up to 30 W |
### Safety system (arm)
EN ISO 10218-1, ISO 13849-1 PL d Cat. 3, 27 safety functions in 8 groups: emergency stop, protective stop, motion state, manual mode, speed monitoring, torque and power limits, collision protection, position monitoring. Stop categories: Cat. 0 (power cut), Cat. 1 (controlled stop, then power off; E-stop button), Cat. 2 (stops on path, stays enabled; safety functions). Details in [11_SAFETY.md](11_SAFETY.md) and [04_ARM.md](04_ARM.md).
---
## 3. Mobile base (AGV)
From the AGV spec sheet, Lumi manual 5.1.4 and the chassis manual.
| Item | Value |
|---|---|
| Size | 510 × 510 × 280 mm |
| Weight | 50 kg |
| Payload | 60 kg rated, 80 kg max on flat floor |
| Drive | Differential, 2 × 160 W hub servo motors |
| Wheels | 2 drive, 4 casters, 1 auxiliary; swing-arm active suspension |
| Turning radius | 307 mm |
| Ground clearance | 25 mm |
| Speed | 0.6 m/s default, 1.2 m/s max (API joystick command limited to ±0.5 m/s, ±1.0 rad/s) |
| Repeatability | ±5 cm |
| Obstacles | Step 15 mm, slope 8°, gap 30 mm; needs a 700 mm wide passage |
| Battery | 24 V (21–29.4 V), 45 Ah Li-ion; about 10 h with ≤ 50 kg load (spec sheet: 45 h idle, 25 h empty driving, 13 h with 60 kg) |
| Battery life | 1000 full cycles to ≥ 75 % |
| Charging dock | 100–240 V AC in, 29.4 V 6 A out |
| Computer | Intel J1900 quad core, Linux (navigation only; not for user code) |
| Mapping | 50 000 m² per map, 80 000 m² max operating area |
| Upper-body recommendations (chassis manual) | total height ≤ 110 cm, centre of mass ≤ 50 cm above ground for full climbing ability; mount through 9 × M5 holes, max 10 mm screw depth |
### Sensors in the base
| Sensor | Specification |
|---|---|
| 2D lidar | 0.02–10 m, 240°, ±20 mm, 10 mm resolution, 30 Hz, IP65 |
| 3D camera (front, looks forward/up) | 0.35–2 m, FoV H 58.4° × V 45.5° |
| Ultrasonic | 5 units, 0.03–0.55 m, ≈ 3 cm accuracy, < 15° cone |
| IMU | 6-axis |
| Infrared | 1 m, ±2–6° |
| Bumper | triggers at 5–7 mm travel, > 20 N |
### Connectors on the back of the base
From the Lumi manual 6.5, the quick manual, web doc 3.2 and the chassis ports docx.
| Connector | Purpose |
|---|---|
| USB 3.0 (1) | **Head camera, torso camera and voice module.** Plug the host computer in here |
| Gigabit Ethernet (RJ45, "upper computer") | Host computer. Fixed `192.168.10.x` network (robot at `192.168.10.90`) |
| USB 3.0 (2) | MiniCab control cabinet inside the base |
| External RJ45 | Extra network port |
| Charging contacts | Contact charging on the dock (LED breathes while charging) |
| 48 V manual charging socket | Behind a magnetic cover on the right side; remove the cable before driving (tasks fail while it is plugged) |
| 48 V and 24 V aviation sockets | Upper-body power |
| Main power switch | Underneath, next to the rear right caster. Off from the factory; "pull" it on at first start |
| Contact power switch | Hidden underneath |
| E-stop | Built into the chassis; another red E-stop button is on the column |
### Lights and buttons
| Base LED strip | Meaning |
|---|---|
| Green flashing | Power on, computer booting |
| White steady | Booted, normal |
| White / blue-white breathing | Charging (also while off and charging) |
| White / blue-white flashing | E-stop pressed |
| Charging dock light | Meaning |
|---|---|
| Green | Dock powered, not charging, or charging with battery ≥ 90 % |
| Red | Charging, battery < 90 % |
Power button: hold → two short beeps (LED purple) → release after the third, long beep (LED flashes green while booting). Off: hold → seven short beeps → release on the eighth, long beep.
**E-stop (red button on the column):** cuts arm power and stops the lift column; the base becomes free to push by hand. After releasing the E-stop the base cannot be pushed any more. (Web doc 3.3.3.4.)
---
## 4. Cameras
| Item | Value |
|---|---|
| Model | Orbbec Gemini 2 L (head and torso), USB VID:PID `2bc5:0673` |
| Depth range | 0.02–10 m (brochure: 0.2–10 m) |
| Depth FoV | H 91° / V 66° / D 101° ± 3° |
| Depth resolution | 1280 × 800 @ 30 fps, 640 × 400 @ 60 fps |
| Colour FoV | H 94° / V 68° / D 104° ± 3° |
| Colour resolution | 1280 × 800 @ 30 fps, 1280 × 720 @ 60 fps |
| Other streams | IR, IMU (accelerometer + gyroscope, ~200 Hz) |
| Interface | USB 3.0 (required; USB 2.0 is not enough) |
Calibrated intrinsics, mount poses and software: [06_CAMERAS_AND_VISION.md](06_CAMERAS_AND_VISION.md).
---
## 5. Voice module
| Item | Value |
|---|---|
| Model | iFlytek AIUI XF-USB-MC (shows up as the audio device `AIUI-USB-MC`) |
| Microphones | 6-mic ring array in the head |
| SNR | > 70 dB |
| Wake-up / recognition distance | 3–5 m (more with an external mic) |
| Sound localisation | 4 mics 180°, 6 mics 360°, ±15° |
| OS support | Windows, Linux, Android |
Use: [07_VOICE_AND_AUDIO.md](07_VOICE_AND_AUDIO.md).
---
## 6. Main AI computer options
JAKA's recommendation (web doc 3.0):
| | No extra controller | Jetson Orin NX | Jetson AGX Orin | Jetson AGX Thor |
|---|---|---|---|---|
| Class | — | light, 70 TOPS | high, 275 TOPS | flagship, 2070 TOPS |
| Use when | No vision or voice; control body, arm, base only; wireless remote control | Body control only, or ≤ 2 × 1080p @ 15 fps light AI | Vision and voice needed, LLM ≤ 7B or VLA ≤ 13B, 4–8 × 1080p @ 30 fps | Large multimodal models (≥ 30B VLA, ACT, LLM + vision), 8K, multi-robot |
| Typical tasks | Trajectory teaching, body + base control, AGV transport, simple palletising | Same | Vision-guided assembly, barcode + OCR, voice picking, online quality check | Voice interaction, ACT 30 Hz end-to-end, complex semantic segmentation, LLM trajectory generation |
| Measured (vendor) | — | YOLOv5n 640×480 25 FPS; Whisper-Tiny 0.8× real time | YOLOv8x 640×640 8 ch 30 FPS; Whisper-Small 1.2× RT; LLaMA-7B INT4 18 tok/s | ACT 512×512 2 cameras 30 Hz; LLaMA-30B INT4 28 tok/s; 8K AV1 60 FPS |
| CPU | — | 6/8-core Cortex-A78AE | 12-core Cortex-A78AE 2.2 GHz | 72-core Arm v9 (Grace-Next) 2.6 GHz |
| GPU | — | 1024-core Ampere | 2048-core Ampere 1.3 GHz | Blackwell 1.57 GHz |
| Memory | — | 8 / 16 GB LPDDR5 | 32 / 64 GB LPDDR5 | up to 128 GB |
| Power | — | 10–25 W | 15–60 W | 30–120 W |
Lumi uses a **Jetson AGX Thor**: [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md).
The vendor's education kit lists: JAKA Mini2 arm, lift + voice module, **DH-PGEA-50** gripper with 3D-printed fingers, lidar base, 3D camera, optional 16" monitor, **Jetson AGX Orin** main controller.
---
## 7. Kinematic model files
| File | Where |
|---|---|
| URDF | JAKA_Lumi `feat_ros` branch: `jaka_lumi_ros/src/jaka_lumi_description/urdf/jaka_lumi.urdf` |
| URDF with cameras, lidar and casters | JAKA_Lumi `main`: `02. .../JAKA-Lumi-sensors-v3/urdf/JAKA-Lumi-sensors-v3.urdf` |
| USD for Isaac Sim | `feat_ros`: `jaka_lumi_description/urdf/jaka_lumi/*.usd` |
| MoveIt 2 config | `feat_ros`: `jaka_lumi_moveit_config/` |
| STEP model (65 MB) and 2D drawing | JAKA_Lumi `main`: `02. .../Lumi Models [模型说明]/` |
Sensor mount poses from the sensors URDF (in `base_link`, whose front is −y):
| Link | Parent | xyz (m) | rpy (rad) |
|---|---|---|---|
| `Camera3_Link` (head camera) | `link_4` | (−0.0552, −0.0665, −0.001) | (−1.5708, −1.5708, 0) |
| `Camera2_Link` (torso camera) | `link_2` | (0.1257, 0.011, 0.0287) | (0, 0, 0) |
| `Camera1_Link` (base camera) | `base_link` | (0.003, −0.191, −0.120) | (−0.663, 0, 3.1416) |
| `Radar_Link` (lidar) | `base_link` | (0, −0.126, −0.085) | (0, 0, 0) |
+133
View File
@@ -0,0 +1,133 @@
# 02. Network and access
How to get a computer onto the Lumi network, which addresses and ports exist, and which web pages and apps to use. Passwords are not in these docs; ask the project owner.
---
## 1. Network map
```
Lumi internal network 192.168.10.0/24
┌──────────────────────────────────────────────────────────────────────────┐
│ 192.168.10.90 robot controller (MiniCab): │
│ - arm SDK (jkrc), JSON commands on :10001 │
│ - Cobo π web UI https://192.168.10.90 │
│ - body API + web UI http://192.168.10.90:5000 │
│ 192.168.10.10 AGV base computer: │
│ - AGV TCP API 192.168.10.10:31001 │
│ - monitor / mapping UI http://192.168.10.10:9001 │
│ - map builder http://192.168.10.10:8809 │
│ 192.168.10.79 internal Wi-Fi router (Cudy WR1200E, access point) │
│ 192.168.10.9 gateway (as shown on the router page) │
└──────────────────────────────────────────────────────────────────────────┘
▲ Wi-Fi "Lumi<serial>" (2.4 GHz and -5G) ▲ RJ45 on the back of the base
│ │
laptop / Jetson Thor (192.168.10.x) ─────────────────┘
+ USB 3.0 cable to the base for the head/torso cameras and the microphone array
```
| Service | Address | Login | Notes |
|---|---|---|---|
| Arm SDK (`jkrc`) | `192.168.10.90` | — | Used by every vendor demo and the ROS arm server |
| Arm JSON command port | `192.168.10.90:10001` | — | TCP, JSON commands without the SDK ([04_ARM.md](04_ARM.md)) |
| Cobo π (arm web app) | `https://192.168.10.90` (also `http://`) | Administrator | Accept the self-signed certificate. Settings, manual jog, external axes, programs |
| Body (lift/waist/head) web UI | `http://192.168.10.90:5000` | none | ExtAxis page: Enable / Disable / Reset / Stop, joint table, chart, Upgrade page |
| Body HTTP API | `http://192.168.10.90:5000/api/extaxis/...` | none | [03_BODY_LIFT_WAIST_HEAD.md](03_BODY_LIFT_WAIST_HEAD.md) |
| AGV TCP API | `192.168.10.10:31001` | none | [05_AGV_BASE.md](05_AGV_BASE.md) |
| AGV monitor and mapping | `http://192.168.10.10:9001` | none | Chrome recommended. Map builder pops up on port 8809 |
| Robot Wi-Fi router admin | `http://192.168.10.79` | password | Cudy WR1200E in access-point mode |
| MiniCab LAN1 (fixed) | `10.5.5.x` (controller at `10.5.5.100` in old docs) | — | Old LumiAPI doc and the VR-teleop defaults use `10.5.5.100` |
| AGV chassis Wi-Fi (alternative) | SSID `admin_xxxxxx` | password | From the chassis manual; Lumi uses its own router instead |
| VR teleop receiver (vendor) | PC port 8018 (docs) / 9852 (launch file) | — | [09_ROS2_TELEOP_AND_SIM.md](09_ROS2_TELEOP_AND_SIM.md) |
Ports summary: `5000` body HTTP, `443/80` Cobo π, `10001` arm JSON commands, `31001` AGV TCP, `9001` AGV web, `8809` AGV map builder, `22` SSH on the Jetson, `8000`/`8080`/`5173` voice-assistant services on the Jetson ([08](08_NVIDIA_THOR.md)).
---
## 2. Connect a computer
### Option A: Wi-Fi
1. Read the serial on the robot's name plate.
2. Join the Wi-Fi `Lumi<serial>` (a 2.4 GHz and a `-5G` network) with the factory-default password.
3. Check your IP address. It must be `192.168.10.x`. If it is `10.5.5.x`, follow "Fix a 10.5.5.x address" below.
4. Test: `ping 192.168.10.90` and `ping 192.168.10.10`, then open `http://192.168.10.90:5000` in a browser.
### Option B: cable
1. Connect your computer to the gigabit RJ45 port on the back of the base.
2. If no address is given by DHCP, set a static address (below), for example `192.168.10.150/24`.
3. Test as above.
For cameras and the microphone, also plug a USB 3.0 cable from the computer into the base's USB 3.0 port (the one for "head/torso cameras and voice module").
### Fix a 10.5.5.x address
When the laptop receives `10.5.5.xxx` (gateway `10.5.5.1`) from the robot Wi-Fi, the robot services do not answer. Set the address by hand:
| Field | Value |
|---|---|
| IP address | a free `192.168.10.x`, e.g. `192.168.10.150` (avoid .9, .10, .79, .90 and addresses already in use) |
| Subnet mask | `255.255.255.0` |
| Gateway | `192.168.10.9` (gateway shown on the robot router) |
| DNS | `192.168.10.9` or leave empty |
**Windows 10/11:** Settings → Network & Internet → Wi-Fi (or Ethernet) → the connection → IP assignment → Edit → Manual → IPv4 on → enter the values → Save. Or: Control Panel → Network and Sharing Center → Change adapter settings → right-click the adapter → Properties → Internet Protocol Version 4 → Use the following IP address.
**macOS:** System Settings → Wi-Fi (or Ethernet) → Details… next to the network → TCP/IP → Configure IPv4: *Manually* → enter IP, mask, router → OK.
**Ubuntu:** Settings → Network → gear icon → IPv4 → Manual → address, netmask, gateway → Apply; or `nmcli con mod "<name>" ipv4.method manual ipv4.addresses 192.168.10.150/24 ipv4.gateway 192.168.10.9 && nmcli con up "<name>"`.
Before choosing an address, check it is free: `ping 192.168.10.150` should not answer.
### Keep internet while on the robot network
Use the cable for the robot and Wi-Fi for the internet (for cloud APIs). On Linux:
```bash
# 192.168.10.* over the wired port, everything else over Wi-Fi
sudo ip route replace 192.168.10.0/24 via 192.168.10.1 dev <wired-iface> metric 50
sudo ip route replace default via <wifi-gateway> dev <wifi-iface> metric 100
sudo ip route del default via 192.168.10.1 dev <wired-iface> 2>/dev/null
```
On macOS: System Settings → Network → "…" → Set Service Order, put Wi-Fi above Ethernet; macOS still reaches `192.168.10.x` through the cable because it is on that subnet.
---
## 3. Apps and tools
| Tool | What for | Where to get it | Platform |
|---|---|---|---|
| Browser (Chrome) | Cobo π, body web UI, AGV web UI | — | any |
| JAKA App (Zu App) v1.7.2 | Arm setup, safety, payload, programs (older UI) | https://www.jaka.com/download (iOS: App Store "JAKA App"; Android; Windows) | Windows / Android / iOS |
| Cobo π | Newer arm UI; served by the controller (≥ 1.7.1) or installed (Windows PC / Android) | Browser to the robot IP, or installer from JAKA | any browser |
| JAKA SDK v2.2.7 | Python / C++ arm control | [zip](https://www.jaka.com/prod-api/common/download/resource?resource=%2Fprofile%2Fupload%2F2025%2F04%2F25%2F20250425134342A024.zip); also inside the JAKA_Lumi repo | Linux x86_64 / aarch64, Windows (no macOS) |
| OrbbecViewer / Orbbec SDK v1.10.8 | Check and tune the cameras | https://github.com/orbbec/OrbbecSDK/releases (Windows exe, Linux amd64/arm64 deb, macOS arm64 viewer zip) | all |
| pyorbbecsdk | Python camera access | https://github.com/orbbec/pyorbbecsdk | Linux, Windows (macOS: verify) |
| SSH client (Terminal, MobaXterm on Windows) | Log into the Jetson Thor | — | any |
| VS Code / Cursor + Docker extension | Develop inside the Jetson containers | — | any |
| PICO Developer Center | Install the VR teleop app | https://developer-cn.picoxr.com/resources/#pdc | Windows / macOS |
JAKA App tablet requirements (JAKA App manual): Android 10–13, Snapdragon 835-class; disable battery saving for the app so the robot does not disconnect when the screen locks.
Cobo π browser requirements: Windows 10 64-bit + Chrome ≥ 110, or Android 13 tablet; Cobo π service package needs controller ≥ 1.7.1 (otherwise upload it through the Zu App: Settings → Version upgrade).
---
## 4. Checklist: is everything reachable?
```bash
ping -c 2 192.168.10.90 # robot controller
ping -c 2 192.168.10.10 # AGV computer
curl -s http://192.168.10.90:5000/api/extaxis/status # body joints JSON
curl -s http://192.168.10.90:5000/api/extaxis/sysinfo # body firmware info
python3 - <<'EOF'
import socket, json
s = socket.create_connection(("192.168.10.10", 31001), timeout=3)
s.sendall(b"/api/robot_status")
print(json.loads(s.recv(65536)))
EOF
```
Open in the browser: `https://192.168.10.90` (Cobo π), `http://192.168.10.90:5000` (body), `http://192.168.10.10:9001` (AGV).
+182
View File
@@ -0,0 +1,182 @@
# 03. Body: lift, waist, head
The four "external axes" (lifting column, waist, head yaw, head pitch). There are three ways to drive them: the web page, the HTTP API, and the external-axis panel in Cobo π. ROS 2 nodes wrap the HTTP API.
Units everywhere: **mm** for the lift, **degrees** for the others.
---
## Joint ranges
| Index | Joint | HTTP API range (Lumi SDK doc) | Hardware (Lumi manual, brochure) | URDF |
|---|---|---|---|---|
| 0 / joint 1 | Lift | 0–300 mm | 0–400 mm | `l_1` 0–0.4 m |
| 1 / joint 2 | Waist rotation | −140…+140° | ±160° | `l_2` ±2.7925 rad |
| 2 / joint 3 | Head yaw (neck) | −180…+180° | ±180° | `l_3` ±3.1415 rad |
| 3 / joint 4 | Head pitch | −5…+35° | −5…35° | `l_4` −0.0872…0.6108 rad |
The vendor web UI can show the lift above 300 mm (355 mm in a vendor screenshot), so some firmware accepts more; use 0–300 mm. The vendor demo config limits the lift to 0–200 mm.
**Lift limit on this robot: 0–105 mm.** The head camera's cable is too short for a higher lift. One constant sets it: `robot/head.py` `LIFT_MAX_MM` (the `moveto()` clamp, `tasks/fetch.py` `LIFT_RANGE` / `LIFT_TRIES` and the dashboard jog follow it).
Head yaw: the dashboard uses the full ±180°; the assistant's head tracking stays within `head.YAW_LIMIT` (±60°). The head pitch sign is not documented by the vendor.
---
## 1. Web page
Open `http://192.168.10.90:5000` → **ExtAxis**.
| Button | Chinese label in vendor docs | Action |
|---|---|---|
| Enable | 上使能 | Enable all 4 joints |
| Disable | 下使能 | Disable |
| Reset | 复位 | Clear joint errors |
| Stop | 急停 | Emergency stop of the axes |
Below: the **Joint State** table (Joint, Enable, Error, Error Code, Position, Velocity, Torque) and a **Joint State Chart**. Side menu: HOME, ExtAxis, Upgrade (firmware upload). When the arm side reports an external-axis error, the reset is still done on this page (web doc 3.3.5).
---
## 2. HTTP API
Base URL: `http://192.168.10.90:5000/api/extaxis` (old documents: `http://10.5.5.100:5000/...`). JSON bodies, `Content-Type: application/json`.
| Method | Path | Body | Purpose |
|---|---|---|---|
| GET | `/sysinfo` | — | Version and serial number |
| POST | `/reset` | `{}` | Clear joint errors |
| POST | `/enable` | `{"enable": 1}` / `{"enable": 0}` | Enable / disable all 4 joints |
| POST | `/moveto` | `{"pos": [lift_mm, waist_deg, head_yaw_deg, head_pitch_deg], "vel": 100, "acc": 100}` | Move all 4 joints. **Blocks** until the motion ends or fails |
| POST | `/stop` | `{}` | Stop the current motion (used by the vendor ROS node; not in the written doc) |
| GET | `/status` | — | Array of 4 joint objects |
`moveto` fields:
| Field | Meaning | Range |
|---|---|---|
| `pos` | Target `[lift, waist, head yaw, head pitch]` | Out-of-range values return an error |
| `vel` | Speed ratio (%) | 0.1–100, clamped |
| `acc` | Acceleration ratio (%) | 1–100, clamped |
Rules: enable first; every call sends all four values, so read `/status` and keep the joints you don't want to move at their current value.
Behaviour of the axes:
- After a power cycle of the controller all four joints are disabled (`"enable": false`) and every `moveto` times out until they are enabled. `robot/head.py` `moveto()` enables them first when any is off.
- At its bottom stop the head pitch reads −5.003° (the lift can read −0.003 mm), just outside the API range; a `moveto` that sends such a value back is rejected. `moveto()` clamps every value into the API ranges.
- The torso camera sits on the same link as the arm base, so the camera-to-arm calibration holds at any lift.
`/status` returns one object per joint: `id`, `pos` (mm or deg), `vel`, `toq` (torque), `enable`, `error`, `ecode`.
Responses (web doc 3.3.4):
```json
{"message": "Axis enabled successfully", "status": 0}
{"message": "Axis move successfully", "status": 0}
```
`status` 0 = success; the vendor code treats `-1` as failure.
### curl
macOS / Linux:
```bash
curl -s http://192.168.10.90:5000/api/extaxis/sysinfo
curl -s -X POST http://192.168.10.90:5000/api/extaxis/reset -H "Content-Type: application/json" -d '{}'
curl -s -X POST http://192.168.10.90:5000/api/extaxis/enable -H "Content-Type: application/json" -d '{"enable": 1}'
curl -s http://192.168.10.90:5000/api/extaxis/status
curl -s -X POST http://192.168.10.90:5000/api/extaxis/moveto -H "Content-Type: application/json" \
-d '{"pos": [5, 0, 0, 0], "vel": 20, "acc": 20}'
curl -s -X POST http://192.168.10.90:5000/api/extaxis/enable -H "Content-Type: application/json" -d '{"enable": 0}'
```
Windows `cmd` (as in the vendor screenshot; `^` continues the line, inner quotes escaped):
```
curl -X POST http://192.168.10.90:5000/api/extaxis/moveto ^
-H "Content-Type: application/json" ^
-d "{\"pos\": [5, 0, 0, 0], \"vel\": 100, \"acc\": 100}"
```
### Python
```python
import requests
BODY = "http://192.168.10.90:5000/api/extaxis"
def body_status():
joints = requests.get(f"{BODY}/status", timeout=2).json()
return [j["pos"] for j in joints] # [lift mm, waist, head yaw, head pitch]
def body_enable(retries=5):
"""Vendor pattern: reset, enable, check, repeat."""
for _ in range(retries):
requests.post(f"{BODY}/reset", json={}, timeout=2)
requests.post(f"{BODY}/enable", json={"enable": 1}, timeout=2)
if all(j["enable"] for j in requests.get(f"{BODY}/status", timeout=2).json()):
return True
return False
def body_moveto(lift=None, waist=None, head_yaw=None, head_pitch=None, vel=20, acc=20):
current = body_status()
target = [v if v is not None else c for v, c in zip((lift, waist, head_yaw, head_pitch), current)]
r = requests.post(f"{BODY}/moveto", json={"pos": target, "vel": vel, "acc": acc}, timeout=120)
r.raise_for_status() # returns when the move is finished
return r.json()
def body_stop():
requests.post(f"{BODY}/stop", json={}, timeout=2)
```
Notes from the vendor code:
- Enabling can need retries (`jaka_integrated.py` tries 5 times).
- `moveto` blocks for the whole motion, so give it a long HTTP timeout. A vendor comment says it "often gets no response": treat a timeout as "unknown", then read `/status`.
- The vendor ROS node considers a move done when the lift is within 1 mm and the other joints within 1° of the target.
### Speeds
Not documented by the vendor. At `vel` 20 a 75 mm lift move takes about 5–9 s.
---
## 3. Cobo π external axes
On controllers with Cobo π the body joints are also registered as external axes of the arm controller:
1. `https://192.168.10.90` → log in.
2. **Settings (设置) → Hardware & communication → External axis settings (外部轴设置)**: four axes of type "positioner" (变位机): 汇川升降 (Inovance lift), 腰 (waist), 脖子 (neck = head yaw), 头 (head = pitch), each with an enable switch.
3. **Manual (手动) → External axis jog (外部轴调节)**: choose the axis, see the current position, type a target and press "Move to target" (移动至目标点), or hold − / +. Speed slider at the bottom.
The newer JAKA SDK (2.3.x, in the LumiCode branch `robohub`) has `ext_power_on`, `ext_enable_on`, `ext_jog_to(axis, pos, vel, acc)` for these axes; the vendor body node used axis 1 = head left/right, 2 = head up/down, 3 = waist left/right, 4 = waist up/down (lift) with ±10 / ±3 clamps. This path is optional; the HTTP API is the documented one.
---
## 4. ROS 2
From the JAKA_Lumi `feat_ros` branch (`jaka_lumi_ros`, ROS 2 Humble, C++ with libcurl, IP hard-coded to 192.168.10.90):
**`jaka_lumi_body_node`** (`ros2 launch jaka_lumi_body_node lumi_body_node.launch.py`)
| Interface | Type | Notes |
|---|---|---|
| `/joint_states` | topic `sensor_msgs/JointState` | `l_1` in metres, others in radians (converted from the API's mm/deg) |
| `/lumi_body/enable` | `std_srvs/SetBool` | |
| `/lumi_body/move` | `jaka_lumi_body_node/MoveService`: `float64[4] target` (mm, deg, deg, deg) → `bool success` | |
| `/lumi_body/stop` | `std_srvs/Empty` | calls `/api/extaxis/stop` |
| `/lumi_body/reset` | `std_srvs/Empty` | |
| `/lumi_body/read_status` | `ReadStatusService` → `float64[4] position` | |
**`jaka_lumi_body_server`**: `FollowJointTrajectory` action server for MoveIt 2 (it also publishes the root of the TF tree, so start it before the arm server). See [09_ROS2_TELEOP_AND_SIM.md](09_ROS2_TELEOP_AND_SIM.md).
---
## 5. Bring-up sequence
1. Read only: `GET /sysinfo`, `GET /status` (firmware version, positions).
2. `reset`, `enable`, then `status` until all `enable` are true.
3. Slow moves with `vel=10`: head pitch 0 → 20 → 0; head yaw 0 → 30 → −30 → 0; waist 0 → 20 → −20 → 0; lift 0 → 50 → 0.
4. `enable 0` at the end.
+336
View File
@@ -0,0 +1,336 @@
# 04. Arm: JAKA Mini 2
How to control the 6-joint arm: the web/app UIs, the Python SDK (`jkrc`), the JSON command port, units, joint space, trajectories, safety settings and the tool connector. Hardware specs are in [01_HARDWARE.md](01_HARDWARE.md#2-arm-jaka-mini-2).
---
## 1. Ways to control the arm
| Tool | Use it for | How |
|---|---|---|
| **Cobo π** (web) | Power on/off, enable, jog, joint/TCP values, safety settings, external axes, programs | Browser → `https://192.168.10.90` → English → select robot → Administrator login |
| **JAKA App 1.7.2** (Zu App) | Same, older UI; required for some settings on 1.7 controllers | https://www.jaka.com/download, join the robot Wi-Fi, connect |
| **Python SDK `jkrc`** | Moves, trajectories, state | Section 3 |
| **JSON command port** (TCP 10001) | Moves, kinematics, tool I/O without the SDK (used by `robot/arm.py`, `robot/gripper.py`) | Section 10 |
| **ROS 2** (`jaka_lumi_minicobo_arm_server`) | MoveIt 2 trajectories | [09_ROS2_TELEOP_AND_SIM.md](09_ROS2_TELEOP_AND_SIM.md) |
Cobo π top bar: Home (首页), Programming (编程), Manual (手动), I/O panel, Settings (设置), Apps (应用); "Real robot" (真机) / simulation switch; checksum; **Power** (电源) and **Enable** (使能) switches on the right; 3PE indicator. The Manual page shows the 3D model, TCP X/Y/Z (mm) and RX/RY/RZ (deg) in the chosen frame ("World frame", "flange centre"), joint dials J1…J6 with a step selector and speed %.
### Power-on order
1. Base main switch on, base power button (see [00_START_HERE.md](00_START_HERE.md)). The robot controller and the arm need about **5 minutes** to be ready after power-on.
2. In Cobo π or the App: **Power** on → ring light blue → **Enable** → ring light green.
3. Power off in the reverse order: disable → power off. Never cut cabinet power while the arm is powered or enabled; wait 5–10 s after the cabinet shuts down before cutting power.
---
## 2. Controller versions: 1.7 vs 3.2
Differences that change how code must be written (JAKA web doc 3.3.5.3):
| | Controller 1.7 (e.g. 1.7.1-46-X64-minicab) | Controller 3.2 |
|---|---|---|
| SDK login | `login()` | `login(1)` (gRPC) |
| Tool TIO RS485 communication | supported | not yet |
| Servo mode (`servo_j`, `servo_p`) | supported | not yet |
| VR teleoperation (vendor) | supported | not supported |
| Cobo π | from 1.7.1 | yes |
| SDK v2.2.7 | needs controller ≥ 1_7_2_28 | — |
The controller version is shown in Cobo π (About / settings) or the JAKA App (About). Vendor code uses both logins (`login(1)` in the BMW demo, `login_in(ip, true)` in the ROS arm server, `login()` in the pick demo): try `login()` first, then `login(1)`.
SDK compatibility (SDK 2.2.7 release notes): SDK 2.2.7 for controllers **1_7_2_28 and newer**; for 1_7_0_x and 1_5_x use SDK 2.1.11 or older.
---
## 3. Python SDK (`jkrc`)
### Get it
| Source | Contents |
|---|---|
| JAKA SDK v2.2.7 zip ([download](https://www.jaka.com/prod-api/common/download/resource?resource=%2Fprofile%2Fupload%2F2025%2F04%2F25%2F20250425134342A024.zip), 63 MB, contains `SDK V2.2.7.7z`) | `Linux/python3/{x86_64,aarch64,i686}-linux-gnu/{jkrc.so,libjakaAPI.so}`, Windows `jkrc.pyd`, C/C++ headers (`JAKAZuRobot.h` documents every function), release notes |
| JAKA_Lumi repo `main` | `JAKA_Lumi_Demo_Case/compose/JAKA_SDK_LINUX_X86`, `JAKA_SDK_LINUX_ARM`, `JAKA_SDK_WINDOWS` |
| jaka-robot-demos `dev/jamie` | `LUMI_DEMO-v1/JAKA_SDK_LINUX/jkrc.pyi` (type stubs with Python signatures) |
| JAKA_Lumi `LumiCode` | `Lumi_Training/JAKASDK/JAKA PythonSDK.pdf` (Python SDK manual v2.1.9, Chinese, 74 pages) |
**No macOS build.** On an Apple Silicon Mac run it in an arm64 Linux container and use the `aarch64-linux-gnu` files:
```bash
# on the Mac (Docker Desktop), from this repo
docker run -it --rm --network host -v "$PWD":/work -w /work arm64v8/python:3.10 bash
# inside the container
export LD_LIBRARY_PATH=/work/jaka_sdk/aarch64:$LD_LIBRARY_PATH # folder with jkrc.so + libjakaAPI.so
python3 -c "import sys; sys.path.insert(0,'/work/jaka_sdk/aarch64'); import jkrc; print(jkrc)"
```
(Docker Desktop's `--network host` needs Docker Desktop 4.34+ with host networking enabled; otherwise the container still reaches `192.168.10.90` through NAT, which is enough for the SDK client.) On aarch64 and x86-64 Linux it runs natively:
```bash
export LD_LIBRARY_PATH=/path/to/JAKA_SDK_LINUX:$LD_LIBRARY_PATH
python3 -c "import jkrc"
```
### Return values and units
Every call returns a tuple; `ret[0] == 0` is success, data is in `ret[1]`.
| Quantity | Unit |
|---|---|
| Joint angles | **rad** |
| Joint speed / acceleration | rad/s, rad/s² |
| Cartesian position | **mm** |
| Cartesian orientation | rad (RX, RY, RZ). Cobo π displays degrees |
| Linear speed / acceleration | mm/s, mm/s² |
| Payload | kg, centroid mm |
| Servo period | `step_num × 8 ms` |
`move_mode`: `0` ABS, `1` INCR, `2` CONTINUE. `coord_type`: `0` base/user, `1` joint, `2` tool.
### Signatures (from `jkrc.pyi` and the Python manual)
```python
robot = jkrc.RC("192.168.10.90")
robot.login() # 1.7 controller; on 3.2 use robot.login(1) (stub name: log_in(use_grpc=0))
robot.logout()
robot.power_on(); robot.power_off(); robot.shut_down()
robot.enable_robot(); robot.disable_robot()
robot.joint_move(joint_pos, move_mode, is_block, speed) # rad, rad/s
robot.joint_move_extend(joint_pos, move_mode, is_block, speed, acc, tol)
robot.linear_move(end_pos, move_mode, is_block, speed) # [x,y,z mm, rx,ry,rz rad], mm/s
robot.linear_move_extend(end_pos, move_mode, is_block, speed, acc, tol)
robot.linear_move_extend_ori(end_pos, move_mode, is_block, speed, acc, tol, ori_vel=pi, ori_acc=4*pi)
robot.circular_move(end_pos, mid_pos, move_mode, is_block, speed, acc, tol)
robot.jog(aj_num, move_mode, coord_type, jog_vel, pos_cmd=0); robot.jog_stop(jnum)
robot.motion_abort()
robot.servo_move_enable(True/False); robot.is_in_servomove()
robot.servo_j(joint_pos, move_mode, step_num) # period = step_num * 8 ms
robot.servo_p(end_pos, move_mode, step_num)
robot.servo_move_use_none_filter()
robot.servo_move_use_joint_LPF(cutoff_hz)
robot.servo_move_use_joint_NLF(max_vr, max_ar, max_jr)
robot.servo_move_use_carte_NLF(max_vp, max_ap, max_jp, max_vr, max_ar, max_jr)
robot.edg_init(en, edg_stat_ip); robot.edg_servo_j(...); robot.edg_servo_p(...)
robot.get_joint_position() # (0, (j1..j6)) rad, commanded
robot.get_actual_joint_position()
robot.get_tcp_position() # (0, (x,y,z mm, rx,ry,rz rad))
robot.get_actual_tcp_position()
robot.get_robot_status() # (0, list) see below
robot.kine_forward(joint_pos); robot.kine_inverse(ref_joint_pos, cartesian_pose)
robot.get_digital_input(type, index); robot.set_digital_output(type, index, value)
robot.get_analog_input(type, index); robot.set_analog_output(type, index, value)
robot.get_tool_id(); robot.set_tool_id(id); robot.set_tool_data(id, tcp, name)
robot.set_payload(...); robot.set_collision_level(level); robot.collision_recover(); robot.clear_error()
robot.drag_mode_enable(bool); robot.is_in_drag_mode()
robot.program_load(name); robot.program_run(); robot.program_pause(); robot.program_resume(); robot.program_abort()
robot.get_sdk_version(); robot.get_last_error(); robot.set_error_handler(func)
```
### `get_robot_status()` list (Python manual 4.4.1)
| Index | Field | Index | Field |
|---|---|---|---|
| 0 | errcode (0 = OK) | 13 | ain (cabinet analog in) |
| 1 | inpos (motion reached) | 14 | tio_dout |
| 2 | powered_on | 15 | tio_din |
| 3 | enabled | 16 | tio_ain |
| 4 | rapidrate | 17 | extio |
| 5 | protective_stop (collision) | **18** | **cart_position** (TCP pose) |
| 6 | drag_status | **19** | **joint_position** |
| 7 | on_soft_limit | 20 | robot_monitor_data (temperatures, voltages, currents per joint) |
| 8 | current_user_id | 21 | torq_sensor_monitor_data |
| 9 | current_tool_id | 22 | is_socket_connect |
| 10 | dout (cabinet) | 23 | emergency_stop |
| 11 | din (cabinet) | 24 | tio_key (`[0]` FREE, `[1]` POINT, `[2]` light button) |
| 12 | aout (cabinet) | | |
Status data refreshes every 4 ms by default.
### Minimal session
```python
import math, jkrc
robot = jkrc.RC("192.168.10.90")
ret = robot.login()
if ret[0] != 0:
ret = robot.login(1) # controller 3.2
assert ret[0] == 0, ret
robot.power_on() # ~8 s
robot.enable_robot() # ~4 s
robot.set_collision_level(1) # 25 N, most sensitive
robot.set_network_exception_handle(100, 2) # abort motion if the SDK link drops for 100 ms
print("joints (deg):", [round(math.degrees(a), 2) for a in robot.get_joint_position()[1]])
print("tcp:", robot.get_tcp_position()[1])
# one joint, +5 degrees, slowly, relative move
robot.joint_move([0, 0, 0, 0, 0, math.radians(5)], 1, True, 0.2)
robot.disable_robot()
robot.power_off()
robot.logout()
```
Speeds are in rad/s (convert from deg/s with `deg / 180 * pi`); start at 0.2–0.5 rad/s.
---
## 4. Joint space: URDF = SDK (high confidence)
URDF joint angles and SDK joint angles are the same numbers:
- The vendor's ROS arm server (`feat_ros/jaka_lumi_minicobo_arm_server`) sends MoveIt trajectories for `l_a1…l_a6` to `servo_j` unchanged and publishes `get_joint_position()` as `l_a1…l_a6` unchanged.
- Forward kinematics of the official URDF (`jaka_lumi.urdf`, identical in JAKA_Lumi `feat_ros`) matches the controller's flange distance from the arm base within about 1 mm. Cobo π's "World" frame includes the mounting angle, so its xyz components are not directly comparable with the URDF base frame.
Before sending URDF-computed angles (MoveIt or own IK) to the robot, run the per-joint direction check in section 9.
Known poses (degrees, SDK = URDF joint space):
| Pose | J1…J6 | Source |
|---|---|---|
| Factory initial position ("手臂出厂初始位置") | `[0, 120, -120, 0, -90, 0]` | BMW demo |
| Pick demo home / pick / place | `[0, 110, -100, 0, -80, -50]`, `[0, 110, -100, 0, 0, -50]`, `[0, 110, -100, 0, -10, -50]` | JAKA_Lumi `feat_demo/body_head/2_moveto.py` |
| Teleop "E demo vertical" default | `[18.24, -80.54, -49.54, -16.99, -78.43, 0]` (rad `[0.3183, -1.4058, -0.8646, -0.2966, -1.3689, 0]`) | LumiCode `teleoperation_control_lumi.py` |
| Vision demo start pose | rad `[1.780, -0.532, -1.075, -0.554, -1.192, 1.244]` | LUMI_DEMO-v1 config |
| MoveIt SRDF `pose_1` | `[0, 0, -90, 0, -90, 0]` | `jaka_lumi.srdf` |
---
## 5. Trajectories
| Method | When | Notes |
|---|---|---|
| `joint_move` (blocking) | Point-to-point, safest | Controller plans the profile. `set_motion_planner(0)` T-curve (speed first) or `1` S-curve (smooth first) |
| `linear_move` | Straight TCP line (approach/retreat) | Avoid near wrist singularities; prefer joint moves when orientation changes a lot |
| `circular_move` | Arcs | |
| `servo_j` streaming | Own trajectories (sampled at 8 ms × n), tracking, MoveIt | Needs servo mode (controller 1.7; **3.2 not yet**). Send the next point immediately; set a filter first |
| ROS 2 `FollowJointTrajectory` | Plan in MoveIt, execute on the robot | Arm server: servo_j with `step_num = dt / 0.008`, filter `servo_move_use_joint_LPF(0.5)` |
Servo-mode recipe (as in the vendor ROS server and teleop):
```python
robot.servo_move_enable(False)
robot.servo_move_use_joint_LPF(0.5) # or servo_move_use_joint_NLF(60, 60, 60) as in teleop
robot.servo_move_enable(True)
for q in trajectory_rad: # one point every 8 ms * step_num
robot.servo_j(q, 0, 1) # absolute, 8 ms
robot.servo_move_enable(False)
```
Teleop also uses Cartesian servo: `servo_move_use_carte_NLF(500, 250, 250, 500, 250, 250)` and `servo_p(pose, 0, step_num)`.
---
## 6. Function reference (C++ header, SDK 2.2.7)
Names are the same in Python.
| Group | Functions |
|---|---|
| Connection, power | `login_in`/`login`, `login_out`/`logout`, `power_on`, `power_off`, `shut_down`, `enable_robot`, `disable_robot`, `get_sdk_version`, `get_controller_ip`, `set_network_exception_handle(ms, 0 keep / 1 pause / 2 abort)`, `set_debug_mode`, `set_SDK_filepath`, `set_errorcode_file_path`, `get_last_error` |
| State | `get_robot_status`, `get_robot_status_simple` (errcode, errmsg, powered_on, enabled), `get_robot_state` (estoped, poweredOn, servoEnabled), `get_joint_position`, `get_actual_joint_position`, `get_tcp_position`, `get_actual_tcp_position`, `get_motion_status`, `is_in_pos`, `is_in_estop`, `is_on_limit`, `is_in_collision`, `get_dh_param`, `get_installation_angle`, `set_installation_angle(x, z)` |
| Motion | `joint_move(pos, mode, block, speed, acc=3.5, tol=0)`, `linear_move(pos, mode, block, speed, accel=500, tol=0, ori_vel=3.14, ori_acc=12.56)`, `circular_move`, `jog`, `jog_stop`, `motion_abort`, `set_rapidrate(0..1)`, `set_motion_planner(-1/0/1)`, `kine_forward`, `kine_inverse` (nearest to the reference joints, error −4 if none), rotation conversions |
| Servo | `servo_move_enable`, `is_in_servomove`, `servo_j`, `servo_p`, filters (`none`, `joint_LPF`, `joint_NLF`, `carte_NLF`, `joint_MMF`, `speed_foresight`), EDG (`edg_init`, `edg_servo_j`, `edg_servo_p`, `edg_get_stat`) |
| Frames, tool, payload | `set_tool_data`, `set_tool_id`, `get_tool_data`, `get_tool_id`, `set_user_frame_data`, `set_user_frame_id`, `set_payload(mass kg, centroid mm)`, `get_payload` |
| Safety, drag | `set_collision_level` (0 off, 1 25 N, 2 50 N, 3 75 N, 4 100 N, 5 125 N), `collision_recover`, `clear_error`, `drag_mode_enable`, `is_in_drag_mode`, `set_motion_limit_warning_range` |
| I/O | `set_digital_output(type, index, value)`, `get_digital_input`, analog in/out, multi-channel variants; types `0` cabinet, `1` tool, `2` extend, `3` relay, `4` Modbus slave, `5` PROFINET, `6` EtherNet/IP |
| Tool RS485 (grippers) | `set_tio_vout_param(enable, 0=24V/1=12V)`, `set_tio_pin_mode`, `set_rs485_chn_comm`, `set_rs485_chn_mode`, `send_tio_rs_command`, `add_tio_rs_signal`, `get_rs485_signal_info` |
| Other | trajectory recording, controller programs, user variables, FTP, force-torque sensor and force control |
### Error codes
| Code | Meaning | Code | Meaning |
|---|---|---|---|
| 0 | success | −16 | FK error |
| 2 | call error / not supported by controller | −20 | protective stop |
| −1 | invalid handle (not logged in) | −21 | emergency stop |
| −3 | connection failed | −22 | on soft limit |
| −4 | no IK solution | −40 / −41 / −42 | linear / joint / arc move error |
| −5 | E-stop pressed | −50 | blocking wait timeout |
| −6 | not powered | −51…−56 | power on/off, enable/disable, user frame, tool timeouts |
| −7 | not enabled | −57 / −58 | EDG init failed / EDG running |
| −8 | not in servo mode | −60 / −61 | IO / operation timeout |
| −9 | must disable first | −9997 / −9998 / −9999 | not implemented / deprecated / obsolete |
| −10 | program running | | |
| −12 | motion abnormal | | |
Full list: https://www.jaka.com/docs/en/guide/errinfo.html
---
## 7. Settings in Cobo π / JAKA App
- **Mounting** (Settings → Operation → Mounting): the arm is mounted on the side of the column (Mounting Orientation Y 90°; do not change it). The 3D model in the UI must match the real arm before moving. The "World" frame shown in the UI includes this mounting angle.
- **Payload** (Settings → Operation → Payload): mass and centre of mass of whatever is on the flange. Wrong values cause false collisions or drift in drag mode. Gripper payload: [10_GRIPPER.md §4](10_GRIPPER.md#4-payload-and-tcp).
- **TCP** (Settings → Operation → TCP, 15 slots): default tool = flange centre (+Z out of the flange, −Y toward the TIO connector).
- **Collision**: force / momentum / TCP speed / power limits; rebound 0–3°. While a program runs, ~1° joint deviation stops the robot, ~3.6° stops and disables it.
- **Joint limits** (Safety → Joint Limit): soft limits and speed limit per joint, within the factory range.
- **Safety zones are NOT active in SDK control mode** (only while a UI program runs). Control code must check its own workspace.
- **Real / Simulation** switch: hardware-in-the-loop simulation on the real controller (arm must be off and disabled to switch). Useful for dry runs.
- **Freedrive limit**: TCP speed in drag mode 50–1500 mm/s.
- **Initial orientation**: user-defined safe pose (Home button).
- **Brake voltage**: required with an external power supply (MiniCab).
- **Monitoring** page: per-joint current, voltage, temperature, torque as % of alarm thresholds.
- **Stored programs** (`.jks`) run from wherever the arm stands: start one only from a known pose with a checked route.
---
## 8. Tool I/O connector (M8, 8-pin, TIO V3)
| Pin | Signal | Wire | Notes |
|---|---|---|---|
| 1 | +24 V | red | 24 V / 12 V selectable or off; 1 A continuous, 2 A peak |
| 2 | DI1 | blue | NPN / PNP |
| 3 | DI2 | green | NPN / PNP |
| 4 | DO1 / RS485-1 A+ | yellow | NPN / PNP / push-pull, ≤ 1 A |
| 5 | DO2 / RS485-1 B− | pink | NPN / PNP / push-pull, ≤ 1 A |
| 6 | AIN1 / RS485-2 A+ | brown | 0–10 V (reads 0–4096; idle ≈ 400–800) |
| 7 | AIN2 / RS485-2 B− | white | 0–10 V |
| 8 | GND | gray | |
RS485 channel 1 (on the DO pins, high speed): Modbus RTU grippers, JAKA torque sensor; baud up to 230400, 8/9 data bits, 1/2 stop bits, odd/even/none parity. Channel 2 (on the AI pins): low speed. Gripper wiring and signals: [10_GRIPPER.md](10_GRIPPER.md).
---
## 9. First-session arm tests
Commissioning checks before running own motions:
1. Cobo π: note controller version, arm model, joint limits and joint speed limits, mounting, payload.
2. SDK: `login` (or `login(1)`), `get_sdk_version`, `get_robot_status_simple`, `get_joint_position`, `get_dh_param` (compare with the URDF).
3. Collision level 1, payload = no tool.
4. For each joint: `joint_move` INCR +5° at 0.2 rad/s, read `get_joint_position`, check that the joint turned in the positive direction of its URDF axis (and as Cobo π's 3D view shows); move back −5°.
5. Go to the factory pose `[0, 120, -120, 0, -90, 0]°` slowly; compare the arm shape with Cobo π's 3D view and with the URDF at the same angles (e.g. in RViz: `ros2 launch jaka_lumi_description lumi_description.launch.py`).
6. Only then run own poses and short trajectories; servo mode only if the controller supports it.
---
## 10. JSON command port (TCP 10001)
Protocol: [JAKA TCP/IP protocol 1.7.2](https://www.jaka.com/docs/legacy172/en/guide/1.7.2/tcpip.html). Commands are JSON objects with `cmdName`.
| Command / topic | Behaviour |
|---|---|
| `get_data` | Full state, including `actual_position` = [x, y, z mm, rx, ry, rz deg] of the flange in the arm base frame (fixed X-Y-Z roll-pitch-yaw, R = Rz·Ry·Rx) and tool I/O (`tio_dout`, `tio_din`, `tio_ain`). Some replies arrive without the state or tool I/O fields, or as the reply to another command: poll again |
| `kine_forward`, `kine_inverse` | `jointPosition` deg, `cartPosition` mm / deg; `kine_inverse` answers `errorCode` −4 when there is no solution. `kine_inverse` may answer with 7 joint values (use the first 6); `kine_forward` may answer without `cartPosition` (ask again) |
| `joint_move` | `relFlag`, `jointPosition`, `speed`, `accel` (°/s², vendor: keep below 720), `tol`, `executing_line_id`, `end_cond`. No jerk or smoothing field |
| `moveL` | `relFlag` 0, `cartPosition`, `speed` mm/s, `accel`, `tol` |
| `set_motion_planner` | `type` −1 (planner off), 0 (T-planning, trapezoid), 1 (S-planning, smooth start and stop). A controller setting |
| `get_motion_state` | `queue`, `active_queue`, `queue_full`, `inpos`, `motion_line`, ... |
| `stop_program` | Stops a running `joint_move` / `moveL` and empties the motion queue. The controller may also stop the arm and close the connection without a reply |
| `motion_abort`, `get_motion_status`, `is_in_pos` | Not available on this port ("function call failed") |
**Motion queue.** `joint_move` and `moveL` answer at once; the controller runs each motion after the previous one has ended. `tol` is "the transition radius between motion paths", default 0 (mm in the `moveL` example). Moves queued back to back shake the whole robot at each via-point and reversal: send one move at a time and wait for it to settle.
**Speed.** Large joint moves run well below the commanded speed (for example J1 60° at 25–40 °/s takes 7–8 s); short moves (about 20°) run at about the commanded speed.
**Wrapped joints.** J1 / J4 / J6 can stand a full turn away from a stored value; `robot/motion.py` picks target ± 360° nearest to the current angle.
**Wrist.** Near J5 ≈ 0 a straight move can turn J4 and J6 about 110° against each other in small steps; `motion.move_linear(path_checked=True)` lets such a move through when the caller has checked the line in 20 steps.
Taught poses are in `data/arm_poses.json`.
+302
View File
@@ -0,0 +1,302 @@
# 05. Mobile base (AGV)
The base drives and navigates on its own (lidar SLAM). It is used two ways: the **web monitor** for mapping, markers and manual driving, and the **TCP API** from code. Specs are in [01_HARDWARE.md](01_HARDWARE.md#3-mobile-base-agv).
---
## 1. Power
1. First start: switch the main power switch underneath (next to the rear right caster) to **I** ("pull" it on).
2. Hold the power button on the base: two short beeps, purple LED, release after the third, long beep; green flashing while booting; **white** when ready.
3. Off: hold the button, seven short beeps, release on the eighth, long beep. Or "shutdown" in the web monitor, or `/api/shutdown`.
4. Main switch to **O** if the robot stands for more than 30 days.
While the base is off but charging, its Wi-Fi may be visible, but nothing answers until it is switched on.
---
## 2. Web monitor (`http://192.168.10.10:9001`)
Use Chrome.
**Status bar (top left):** map name / floor, battery %, soft E-stop and hard E-stop state, move state (`idle`, `running`, ...), target marker, chassis serial number, software version.
**Top menu:** floor selector, track (keep the robot centred), laser, ultrasonic, infrared, 4g, **position correction**, **add marker** (at current position / at a chosen location), add line (no-go line), add zone, add route (beta), **control** (drive with the keyboard), measure, global path, particle cloud, log, other, **soft E-stop**.
**Bottom menu:** network, restart software, power off and restart, shutdown, update & diagnose, **map management**, configuration, sensor status, test tools, elevator tools, map tools, deployment-detection, robot-3d.
### 2.1 Prepare the area (web doc 3.4.1)
- Close the area with hard boards; avoid reflective material; boards must be at lidar height (inside the scan range).
- Make it a closed polygon (a rectangle is best).
### 2.2 Create a map
1. Bottom menu → **map management** → tab **Map Creating**.
2. Enter **Map Name** (e.g. `office_0301`) and **floor** (e.g. `1`) → **Create Map**.
3. Choose the map size: **small map** (< 3600 m²), **middle map** (3600–10 000 m²), **big map** (> 10 000 m²). Tabs "v1 scanning / v2 scanning" are at the top.
4. The map builder opens (port 8809). Drive the base by hand with the keyboard: **i** forward, **k** back, **j** turn left, **l** turn right. Keep about 0.5 m from the walls, steady speed (≤ 0.5 m/s; slider at the top), turn 360° in each corner to help feature matching. ("start" on the right runs an automatic scan; manual driving is recommended.)
5. Watch "optimizing progress"; press **Save** when done. A page `192.168.10.10:8809/map-build/map.html?hotelid=<map>&floor=1&map_type=v2` opens (buttons "continue scan" / "rescan"); close it.
### 2.3 Use the map
1. Map management → **Switch Map** → choose the map name and floor → **Apply** (the page `192.168.10.10:9001/robot-map-config.html`).
2. Close map management and check the new map on the main page.
### 2.4 Position correction (relocalise)
When the robot icon on the map is not where the robot really is (for example after switching maps, after pushing it while off, or after starting away from the dock):
1. Top menu → **position correction**.
2. Click at the robot's real position on the map and drag in the direction it faces.
3. A dialog appears. Black lines = walls from the map; red = what the lidar sees now; purple = the copy you are moving.
4. Move the purple copy onto the black lines with the buttons or keys: **i** up, **k** down, **j** left, **l** right, **u** rotate clockwise, **o** rotate counter-clockwise. Then **OK**.
It is enough to be within about 20 cm and 5°; the base refines the rest. If the robot is on its dock and a dock marker exists, it snaps to the dock marker automatically.
### 2.5 Add markers (named goals)
1. Drive to the place: top menu **control** on, keys **i / k / j / l**, then **control** off.
2. Top menu **add marker → insert marker at current position** (or "at specified location": click and drag for the heading).
3. In **edit marker**: **Marker type** and **Marker name** (≤ 50 characters), optional icon → **Save**.
Marker types:
| Type | Name | Attributes | Use |
|---|---|---|---|
| 0 | Normal point | — | Go to this pose, nothing else |
| 3 | Lift outside | lift module number | Wait for and call the lift here |
| 4 | Lift inside | lift module number | Position inside the lift (same relative position on every floor) |
| 7 | Gate / door | ID, distance, one-way | Gate or automatic door control point; arrow at 90° to the passage |
| 8 | Lift waiting point | lift number | Needed with several lifts and robots |
| 11 | Charging dock | dock number, charging-pile type | Where the dock really stands; number from the dock's label |
| 20 | Narrow-area waiting point | — | Wait outside a narrow area |
| 76 | Slow-down point | ratio, distance, one-way | Slow down near slopes or thresholds (default ±50 cm) |
Example dock marker: type `11` → the name is filled in automatically (`charge_point_1F_<dock number>`), num = dock number, "common charging pile" → Save. Markers on the map are shown as `name[type][num]`. Every name must be unique (also across floors).
### 2.6 Drive and navigate from the web page
- **control** mode: keys **i j k l**, or click a point on the map to drive there.
- Navigation test: right-click a target on the map; the base plans a green path and drives.
- One marker: show it ("display point") and send the move. Several markers: **test tools** → choose markers, repeat count → run.
---
## 3. TCP API
### Protocol
- TCP client to **`192.168.10.10:31001`** (or the base's LAN IP when it joined another Wi-Fi via the API). Socket, not serial.
- Commands are URL-like strings; replies are JSON.
- Add `uuid=<anything>` to a command and the reply carries it back.
- Reply `type`: `response` (to your command), `callback` (data you subscribed to), `notification` (events pushed to all clients).
- Reply `status`: `OK`, `INVALID_REQUEST`, `REQUEST_DENIED`, `UNKNOWN_ERROR`, `GOAL_CAN_NOT_BE_REACHED`; reason in `error_message`.
```python
import json, socket, uuid
AGV = ("192.168.10.10", 31001)
def agv(command, timeout=5.0):
"""Send one command, return its response (skips callbacks/notifications on the same socket)."""
tag = uuid.uuid4().hex
command += ("&" if "?" in command else "?") + f"uuid={tag}"
buf = ""
with socket.create_connection(AGV, timeout=timeout) as sock:
sock.sendall(command.encode())
dec = json.JSONDecoder()
while True:
buf += sock.recv(65536).decode()
while buf.strip():
try:
msg, end = dec.raw_decode(buf.lstrip())
except json.JSONDecodeError:
break # partial message, read more
buf = buf.lstrip()[end:]
if msg.get("type") == "response" and msg.get("uuid") == tag:
return msg
print(agv("/api/robot_status"))
```
### Direct velocity control: `/api/joy_control`
```
/api/joy_control?linear_velocity=0.2&angular_velocity=0.5
```
| Parameter | Unit | Range | Sign |
|---|---|---|---|
| `linear_velocity` | m/s | −0.5…0.5 (clamped) | + forward |
| `angular_velocity` | rad/s | −1.0…1.0 (clamped) | + turn left (counter-clockwise) |
- **One command lasts 0.5 s**, then the base stops. Send at > 2 Hz (10 Hz recommended) for continuous motion.
- Overrides navigation (`/api/move`).
- Vendor keyboard example: every 0.1 s, v = 0.5 m/s, w = 0.3 rad/s.
```python
import time
def drive(v, w, seconds, rate=10):
t_end = time.time() + seconds
while time.time() < t_end:
agv(f"/api/joy_control?angular_velocity={w}&linear_velocity={v}")
time.sleep(1 / rate)
```
### Navigation
| Command | Parameters | Notes |
|---|---|---|
| `/api/move?marker=NAME` | `marker`, or `location=x,y,theta` (map frame, m, rad); optional `max_continuous_retries` (30), `distance_tolerance` (m), `theta_tolerance` (unit: degrees in the official manual, radians in a translation; not confirmed), `angle_offset` (rad, −3.14…3.14), `yaw_goal_reverse_allowed` (1/0), `occupied_tolerance` (m) | Plans a path and avoids obstacles. Returns `task_id`. Rejected while another move is `running` |
| `/api/move?markers=m1,m2,m3&count=-1&distance_tolerance=1.0` | ≥ 2 markers, count (−1 forever; default 1), tolerance ≥ 0.5 m (default 0.5), `max_continuous_retries` (default 5) | Patrol; a failed point is skipped and the patrol continues; stop it with `/api/move/cancel` |
| `/api/move/cancel` | — | Stop the task and stay (the manual: stops on the spot and waits for the next move). The manual v1.8.8 has no pause / resume command and no footprint, padding or inflation parameter on `/api/move` or `/api/set_params` (only `max_speed_linear`, `max_speed_angular`; `occupied_tolerance` is how near an occupied goal it may stop) |
| `/api/get_planned_path` | — | Points of the current global path |
| `/api/make_plan?start_x=..&start_y=..&start_floor=..&goal_x=..&goal_y=..&goal_floor=..` | | Path length between two points |
Wait for a move to finish (vendor pattern): poll `/api/robot_status` every 0.1–0.5 s until `results.move_status == "succeeded"` (or `failed` / `canceled`).
### State
| Command | Returns |
|---|---|
| `/api/robot_status` | `move_target`, `move_status` (`idle` / `running` / `succeeded` / `failed` / `canceled`), `running_status` (e.g. `leave_charging_pile`, `dock_to_charging_pile`, lift states), `move_retry_times`, `charge_state`, `soft_estop_state`, `hard_estop_state`, `estop_state`, `power_percent`, `current_pose {x, y, theta}` (m, rad), `current_floor`, `chargepile_id`, `error_code`. Poll at 1–2 Hz |
| `/api/robot_info` | `product_id` |
| `/api/get_power_status` | `battery_capacity` %, `battery_current` (A, + charging), `battery_voltage`, `charge_voltage`, `charger_connected_notice`, `head_current` |
| `/api/diagnosis/get_result` | Self-test: sensor board, motor boards, radio, power, depth camera, laser, IMU, CAN, internet |
| `/api/software/get_version` | Software version (`check_for_update`, `update`, `restart` also exist) |
### Real-time streams: `/api/request_data?topic=...&frequency=Hz`
| Topic | Default | Data |
|---|---|---|
| `robot_status` | 2 Hz | as `/api/robot_status` |
| `human_detection` | 1 Hz | `"legtrack N": {"position": {x, y}, "velocity": {x, y}}` in the robot frame (x ahead, right-handed, so y left). **Needs the leg-tracking module configured and enabled** |
| `robot_velocity` | 1 Hz | `linear` (m/s, + forward), `angular` (rad/s, + left) |
Keep the socket open to receive the callbacks.
### Markers
| Command | Notes |
|---|---|
| `/api/markers/insert?name=N&type=0&num=1` | At the current pose. Custom types > 1000 |
| `/api/markers/insert_by_pose?name=N&x=..&y=..&theta=..&floor=..` | At given coordinates |
| `/api/markers/query_list`, `/api/markers/query_brief`, `/api/markers/count` | List |
| `/api/markers/delete?name=N` | Delete |
| `/api/position_adjust?marker=N`, `/api/position_adjust_by_pose?x=..&y=..&theta=..` | Relocalise (only after drift) |
### Settings and other
| Command | Notes |
|---|---|
| `/api/set_params?max_speed_linear=0.3&max_speed_angular=0.5` | 0.1–1.0 m/s, 0.5–3.5 rad/s; reset at restart; always answers `OK`, confirm with `/api/get_params` |
| `/api/estop?flag=true` / `false` | Software E-stop (motors free, base can be pushed). Separate from the hardware E-stop; neither releases the other; reset to false at restart |
| `/api/map/list`, `/api/map/get_current_map` (resolution, width, height, origin), `/api/map/set_current_map?map_name=..&floor=..`, `/api/map/list_info` | Maps (setting a map restarts the base service) |
| `/api/map/accessible_point_query?x=..&y=..`, `/api/map/distance_probe?x=..&y=..` | Nearest reachable point; distance to obstacles |
| `/api/LED/set_color?r=..&g=..&b=..` (0–100), `/api/LED/set_luminance?value=..` | Base LED strip |
| `/api/shutdown?reboot=false&delay=0` | Off after 10 s |
| `/api/wifi/list`, `/api/wifi/connect`, `/api/wifi/get_active_connection`, `/api/wifi/info`, `/api/wifi/detail_list` | Base Wi-Fi |
| `/api/lift_status` | Only while riding a lift |
**Notifications** (pushed; do not use for flow control): full code list in [3.2](#32-further-details-from-the-agv-api-manual).
### 3.1 Differences on this base
Base software 0.10.351.1D is newer than the API manual: `task_id` comes inside `results`, and `robot_status` has extra fields (`chassis_lift_state`, `collision_state`, `hall_state`, `hand_charge`, `hard_estop_abolish_state`, `is_paused`, `extraData`, `outTaskId`, `target_floor`, `task_id`, `ts`).
### 3.2 Further details from the AGV API manual
Source: `AGV API手册.pdf` (69 pages, Chinese; document v1.8.8 of 2022-03-18, in the JAKA_Lumi repo). Some fields differ on this base (3.1).
**Protocol notes**
- Replies are JSON; fields at the same level have no fixed order, parse them with a JSON parser.
- Socket is recommended; a serial link is also possible but can corrupt data.
- Old address format: since v1.4.0 the `http://192.168.10.10:8808` prefix was dropped from the commands, and the manual says the original format "can still be used", i.e. `http://192.168.10.10:8808/api/robot_status` over HTTP. Not confirmed on this base.
- `error_code` in `robot_status`: hexadecimal string of 8 bytes; anything other than `"00000000"` means a fault.
**`running_status` values** (`move_status` in brackets): `idle` (idle/succeeded/failed/canceled), `leave_charging_pile`, `dock_to_charging_pile`, `leave_container`, `dock_to_container`, `leave_cabin`, `dock_to_cabin`, `goto_lift`, `wait_lift_unlock`, `wait_lift_outside`, `enter_lift`, `avoid_lift`, `take_lift`, `exit_lift`, `back_to_lift` (all running), `running` (any other running state). Do not cancel a move during `enter_lift`, `avoid_lift`, `take_lift`, `exit_lift`.
**`/api/robot_info`** → `{"results": {"product_id": "WATER-xxxx-xxxxx"}}` (base serial; software ≥ 0.6.3.3).
**Markers**
| Command | Parameters | Reply |
|---|---|---|
| `/api/markers/insert` | `name` (no special characters), `type` (int, default 0), `num` (int, default 1) | marker at the current pose and floor. Examples: `?name=205_room`, `?name=charge_dock_2&type=11` |
| `/api/markers/insert_by_pose` | `name` (an existing name is updated), `x`, `y` (map, float), `theta` (float, −π…π), `floor` (int ≠ 0, default current floor), `type` (default 0), `num` (default 1) | `?name=205_room&x=-0.1&y=1.0&theta=0.0&floor=2&type=0` |
| `/api/markers/query_list` | `floor` (optional; all floors otherwise) | `results` = `{name: {"floor", "pose": {"orientation": {x, y, z, w}, "position": {x, y, z}}, "key": type, "marker_name"}}`; `null` if there are no markers. This base also returns `avatar` (icon) |
| `/api/markers/count` | — | `{"results": {"count": 10}}` |
| `/api/markers/query_brief` | — | `{"results": {"meeting_room": "0-1", ...}}` = `"type-floor"` per name |
| `/api/markers/delete` | `name` | `OK`; unknown name → `status: "INVALID_REQUEST"`, `error_message: "Marker Not Found"` |
Marker types usable through the API: `0` normal, `1` front desk, `3` lift outside, `4` lift inside, `7` gate, `11` charging dock; other types should be created in the web monitor. Custom types must be > 1000.
Quaternion → `theta` (from the manual):
```python
import math
def quat_to_theta(z, w):
theta = 2 * math.atan2(z, w)
if math.pi < theta <= 2 * math.pi:
theta -= 2 * math.pi
elif -2 * math.pi <= theta < -math.pi:
theta += 2 * math.pi
return theta
```
**Wi-Fi of the base**
| Command | Parameters | Reply |
|---|---|---|
| `/api/wifi/list` | — | `{"SSID1": 50, ...}` (SSID → signal strength) |
| `/api/wifi/connect` | `SSID`, `password` (optional if connected before) | joins / switches the environment Wi-Fi |
| `/api/wifi/get_active_connection` | — | current SSID, `""` if none |
| `/api/wifi/info` | — | `{"IPaddr": "...", "HWaddr": "..."}` (IP from the environment Wi-Fi) |
| `/api/wifi/detail_list` | — | per SSID: `SSID`, `SIGNAL`, `ACTIVE`, `FREQ` (e.g. "2462 MHz"), `SECURITY` (e.g. "WPA2", empty = open) |
After joining another Wi-Fi, the API is also reachable at that IP (port 31001).
**Other replies**
- `/api/software/get_version` → `{"results": "x.x.x"}`.
- `/api/map/set_current_map?map_name=<name>&floor=<n>` (`hotel_id` is the deprecated name of `map_name`); the base service restarts, so a reply may not arrive.
**Notifications (`"type": "notification"`)**: fields `code` (stable ID), `description` (English), `level` (`info` / `warning` / `error`), `data` (extra info, e.g. `{"target": "room_205"}`; task-end notifications carry the distance driven). Poll `robot_status` for decisions; notifications can be lost.
| Group | Codes |
|---|---|
| Move task | `01001` started, `01002` finished, `01003` failed, `01004` canceled, `01005` retried, `01006` robot may be trapped (help needed), `01007` no available path (then `01003`) |
| Charging dock | `01010` leaving dock, `01011` left, `01012` failed to leave, `01013` leave retry; `01020` docking started, `01021` docked, `01022` docking failed, `01023` docking data invalid, `01024` no docking feature found, `01025` no power signal, `01026` no infrared signal, `01027` docking timeout |
| Container / cabin | `01028` wrong cabin ID, `01029` lateral mode failed, `01050–01053` leave container, `01060–01062` dock to container, `01070–01073` leave cabin, `01080–01082` dock to cabin |
| Gate / door, narrow area | `01030` door control started, `01031` finished, `01032` door control timeout (released); `01033` waiting for a narrow area, `01034` narrow area free |
| Patrol | `01101` started, `01102` finished, `01103` failed (last point failed), `01104` canceled |
| Path / traffic | `01200` traffic busy, `01201` trapped in an unknown (grey) area, `01202` trapped near an obstacle, `01203` global planning failed (about every 5 s while stuck), `01204` local planning failed, `01210` no-entry sign detected, zero velocity |
| Lift | `04000–04002` go to lift, `04010–04013` call lift (`04013` > 3 min), `04020–04023` ride (`04023` > 3 min), `04030–04033` enter (`04033` not enough space, next lift), `04040–04041` avoid lift, `04050–04052` exit, `04060–04062` back to lift, `04070–04071` wait for unlock |
| State | `02000` power off, `02001` charging on, `02002` charging off, `02003` E-stop on, `02004` E-stop off, `02005` attitude correction triggered (robot may have been moved), `02006` software shutting down, `02010` robot may be lost (`probability`; can be a false alarm) |
| Abnormal | `03001` foreign object in the lidar slot |
---
## 4. Environment rules (chassis manual)
- Indoors, flat floor, no drops over 1.5 cm, thresholds under 1.8 cm, slopes within 8°.
- Lidar blind spots: obstacles lower than about 23 cm (8 cm with a downward camera on the upper body), reflective, black or transparent objects, objects under 2 cm.
- Map drift: carpets over 0.5 cm, wet floors, large empty halls, often-moved furniture, fast driving over bumps, pushing the base while on, starting away from the dock.
- Draw no-go lines around areas the robot must not enter (0.5 m from danger), slow-down zones at slopes, drop zones at stairs.
- Dock against a wall, 0.5 m free each side, ≥ 1.5 m between docks, fixed in place.
---
## 5. First-session base tests
Commissioning checks:
1. Web monitor: map loaded? position correct? battery? E-stops off?
2. API read-only: `robot_status`, `get_power_status`, `software/get_version`, `map/get_current_map`, `markers/query_brief`, `diagnosis/get_result`.
3. In a clear area: `joy_control` 0.1 m/s for 2 s at 10 Hz, then 0.3 rad/s for 2 s. Compare `robot_velocity` and `current_pose`.
4. Try the soft E-stop on and off.
5. Subscribe to `human_detection`, walk around the robot, log positions (shows whether leg tracking is enabled).
6. Create a marker, `/api/move?marker=...`, poll until `succeeded`.
+253
View File
@@ -0,0 +1,253 @@
# 06. Cameras and vision
Two Orbbec Gemini 2 L RGB-D cameras (head and torso) connect to the Jetson Thor over USB 3.0. The base camera belongs to the AGV and is used only by its navigation. Camera specifications: [01_HARDWARE.md](01_HARDWARE.md).
| # | Camera | Mounted on | Moves with |
|---|---|---|---|
| 1 | Head camera (Gemini 2 L) | head, `link_4` | head yaw and pitch, waist, lift |
| 2 | Torso camera (Gemini 2 L) | under the handle on the column, `link_2` | waist, lift (same link as the arm base) |
| 3 | Base camera (AGV 3D sensor) | base front | the base; not accessible |
Roles: the head camera watches people while Lumi stands; the torso camera watches the path while driving and is used for objects, picking and calibration. Either camera stands in for the other while it gives no detections (`assistant/lumi.py` `Vision.pick`).
---
## 1. Connect and check
1. USB 3.0 cable from the computer to the base's USB 3.0 port for "head/torso cameras and voice module". USB 3.0 is required: depth runs only on a 5000M link. Check with `cat /sys/bus/usb/devices/*/speed` (5000 for both cameras).
2. Linux: `lsusb` shows each camera as `2bc5:0673 Orbbec 3D Technology International, Inc Orbbec(R) Gemini 2 L(TM)`.
3. udev rule (once): `SUBSYSTEM=="usb", ATTR{idVendor}=="2bc5", MODE="0666"` in `/etc/udev/rules.d/99-orbbec.rules`.
4. In a VM (VMware): accept "Connect to virtual machine" for each "Orbbec Gemini 2 L" device; plug in before starting the VM or container.
5. In Docker: pass `--device=/dev/bus/usb:/dev/bus/usb` (and `--privileged` or the udev rules), as in the vendor compose files.
### OrbbecViewer
1. Download from https://github.com/orbbec/OrbbecSDK/releases (v1.10.8 in the vendor doc):
- Windows: `OrbbecSDK_v1.10.8_win64.exe` (SDK + viewer) or `OrbbecViewer_v1.10.8_..._win_x64_release.zip`
- Ubuntu x64: `OrbbecSDK_v1.10.8_amd64.deb`
- Jetson / ARM64: `OrbbecSDK_v1.10.8_arm64.deb`
- macOS (Apple Silicon): `OrbbecViewer_v1.10.8_..._macos_arm64_release.zip`
- Install guide: https://github.com/orbbec/OrbbecSDK/blob/main/doc/tutorial/English/Installation_guidance.md ; viewer manual: `OrbbecSDK/doc/OrbbecViewer/English/OrbbecViewer.md`
2. The device list shows "Orbbec Gemini 2 L SN:<serial> USB3.0".
3. Streams: Color, Depth, IR, IMU (about 199 fps), point cloud.
4. Each camera's serial number is also printed next to the QR label on the camera; cover one lens to tell head from torso.
The camera service (§3) must be stopped before any other program opens the cameras.
---
## 2. Python (pyorbbecsdk)
Lumi uses `pyorbbecsdk2` from pip (in `.venv`). Source and examples: https://github.com/orbbec/pyorbbecsdk. Built from source on Linux:
```bash
sudo bash ./scripts/install_udev_rules.sh
sudo udevadm control --reload-rules && sudo udevadm trigger
export PYTHONPATH=$PYTHONPATH:$(pwd)/install/lib/
python3 examples/depth_viewer.py # test
```
Read colour + depth from a camera chosen by serial:
```python
import numpy as np
from pyorbbecsdk import Context, Pipeline, Config, OBSensorType, OBAlignMode, OBFormat
def open_camera(serial=None):
devices = Context().query_devices()
for i in range(devices.get_count()):
dev = devices.get_device_by_index(i)
if serial is None or dev.get_device_info().get_serial_number() == serial:
return Pipeline(dev)
raise RuntimeError(f"camera {serial} not found")
pipe = open_camera("<serial>")
cfg = Config()
cfg.enable_stream(pipe.get_stream_profile_list(OBSensorType.COLOR_SENSOR).get_default_video_stream_profile())
cfg.enable_stream(pipe.get_stream_profile_list(OBSensorType.DEPTH_SENSOR).get_default_video_stream_profile())
cfg.set_align_mode(OBAlignMode.SW_MODE) # depth aligned to colour (HW_MODE also possible on Gemini 2 L)
pipe.enable_frame_sync()
pipe.start(cfg)
frames = pipe.wait_for_frames(1000)
depth = frames.get_depth_frame()
if depth.get_format() == OBFormat.Y16:
h, w = depth.get_height(), depth.get_width()
depth_mm = np.frombuffer(depth.get_data(), np.uint16).reshape(h, w) * depth.get_depth_scale()
color = frames.get_color_frame() # convert with frame_to_bgr_image() from the Orbbec examples (utils.py)
pipe.stop()
```
Vendor wrappers: `orbbecCamera.py` (`Camera(serial_number=...)`, `getColorImage()`, `getColorDepthData()` with depth clipped to 20–10 000 mm and a temporal filter), `multi_camera_manager.py` (several cameras by serial), `cam_diagnose_devices.py` / `diagnose_devices.py` (USB diagnostics). All in jaka-robot-demos `dev/jamie` (LUMI_DEMO-v1 and v3) and JAKA_Lumi `main` (`LUMI_DEMO_BMW/LumiAgent/OrbbecSDK/`).
Linux V4L2: the cameras also appear as `/dev/video*` (the NanoOWL demo uses `--camera 4 --resolution 1280x800`).
### ROS 2
`OrbbecSDK_ROS2` (JAKA_Lumi branch `LumiCode`, `Lumi_Teleoperation/src/OrbbecSDK_ROS2`, SDK 1.10.16 libraries for x64 / arm64): `gemini2L.launch.py`, `multi_camera.launch.py`, and the vendor's `multi_gemini2L_synced_sn_template.launch.py` (put each camera's serial in it, then `colcon build`). Config: `config/gemini2L_params.yaml`.
---
## 3. Camera service (`vision/camview.py`)
The camera service is the only program that opens the Orbbec cameras; everything else reads its output. Two programs opening the cameras at once make the SDK reset the devices.
```bash
.venv/bin/python vision/camview.py --serve # started by api/server.py at boot
.venv/bin/python vision/camview.py --stop # free the cameras; stays off until --serve or --start
.venv/bin/python vision/camview.py --start
```
Output in `/dev/shm`, per camera (`<cam>` = `head` or `torso`):
| File | Content |
|---|---|
| `lumi_raw_<cam>.jpg` | full-size colour frame (1280 × 720), every frame |
| `lumi_intr_<cam>.json` | colour intrinsics of the running mode (`camview.intrinsics(name)`) |
| `lumi_det_<cam>.json` | detections of every frame: people with boxes, frame size, head yaw; torso also objects measured by `vision/objects.py` |
| `lumi_cam_<cam>.jpg` / `.json` | picture with boxes and people, for the dashboard |
| `lumi_focus_<cam>.json` | written by clients: the person drawn as focus |
Programs that need people use `RemoteDetector` (same `read()` as `person.PersonDetector`). With no reader, detection drops to 1 frame per second.
Operation:
- After `--stop` / `--start` the torso camera may be missing for a few seconds while it re-enumerates (`camera 'torso' not found`): wait and start again.
- A camera opened on a USB 2 link stays colour-only. After cable work, check the link speed (5000) and restart the service to get depth.
Detector: YOLOv8s on the GPU (TensorRT engine `models/yolov8s.engine`), 4–13 ms per frame; CPU fallback YOLOv8n (OpenCV DNN), about 50 ms. The engine is bound to the TensorRT version and GPU it was built on; `person.load_net()` falls back to the CPU and prints why. Building the models: [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md#7-models-and-local-files).
---
## 4. Intrinsics and extrinsics
### Vendor calibrations
Gemini 2 L colour at 1280 × 720, from the vendor's calibrations of their own robots:
| Camera / file | fx | fy | cx | cy | Distortion k1 k2 p1 p2 k3 |
|---|---|---|---|---|---|
| Torso ("hand") camera, `CalibParams-lumi-hand.json` | 609.91 | 609.62 | 638.99 | 365.77 | −0.00962, −0.04825, 0.00200, 0.00015, 0.07460 |
| Head camera, `CalibParams-head0717.json` | 610.45 | 610.56 | 638.65 | 389.06 | −0.02081, 0.01850, 0.00138, 0.00023, −0.00596 |
These give a horizontal FoV of about 92.7° and a vertical FoV of about **61°** at 1280 × 720 (spec: H 94° / V 68° at 1280 × 800).
The same files contain the camera → arm-base transform (eye-to-hand):
| File | Translation (mm) |
|---|---|
| torso `CalibParams-lumi-hand.json` | (5.8, 217.8, −33.4) |
| head `CalibParams-head0717.json` | (81.9, 96.3, 345.8), valid only at the head pose used for that calibration |
The torso camera and the arm both sit on the waist link, so the torso calibration holds at any waist or lift position. The head camera moves relative to the arm (head yaw / pitch), so its transform needs the head joints in the chain.
Mount poses from the sensors URDF: [01_HARDWARE.md](01_HARDWARE.md).
### This robot
| | Torso camera | Head camera |
|---|---|---|
| Colour intrinsics, 1280 × 720 (factory, from `/dev/shm/lumi_intr_<cam>.json`) | fx 608.3, fy 608.4, cx 636.9, cy 363.2 | fx 607.0, fy 607.2, cx 639.1, cy 365.6 |
| Camera → arm base | `data/camera_extrinsics.json` | `data/camera_extrinsics_head.json` (with the body pose it holds for) |
| Hand-eye accuracy (median) | 3.3 mm | 6.0 mm (max 14.2 mm) |
Head camera transform (`vision/head_cam.py`):
- Reference body pose: lift 0, waist −20.3°, head yaw 0°, pitch −5°. Camera at (−114.1, 68.7, 402.6) mm in the arm base frame.
- Head axes in the arm base frame: yaw axis through (−83.1, −26.5, −142.1) mm, direction (−0.017, −0.014, 1.000); pitch axis through (33.2, 6.4, 355.7) mm, direction (0.995, 0.099, −0.005).
- Valid range: yaw −30…0°, pitch −5…+4° (model within 11 mm / 1.4°). Outside it the model is extrapolated.
- `python vision/head_cam.py measure yaw|pitch` measures an axis (the arm holds the marker still while the head turns); `fit` computes both axes into `data/camera_extrinsics_head.json`.
### Calibration tool (`vision/calib.py`)
Eye-to-hand with an ArUco marker on the gripper. Pose angles follow `get_data` `actual_position`: fixed X-Y-Z roll-pitch-yaw, R = Rz·Ry·Rx (`calib.rpy_matrix()`, `flange_pose()`). OpenCV 5.0 on the Thor has no `cv2.calibrateHandEye`; `calib.py` has its own AX = XB solver with least-squares refinement.
| Command | Does |
|---|---|
| `calib.py collect` | the arm is moved by hand; each still pose with the marker in view is saved (Lumi says "Saved, N") |
| `calib.py solve` | computes the camera → arm-base transform |
| `calib.py check` | live difference in mm between camera and arm |
| `calib.py clear` | deletes the samples |
`--camera head` works on the head camera (samples in `data/calib_samples_head/`); the torso samples are in `data/calib_samples/`.
### Pixel → 3D → arm base
```
x_n = (u - cx) / fx, y_n = (v - cy) / fy
P_camera = depth_mm * [x_n, y_n, 1]
P_base = R_camera_to_base @ P_camera + T_camera_to_base
```
If the depth at a pixel is 0, the vendor code (`utilfs/tools.py`, `generatorNearPoints`) searches nearby pixels.
---
## 5. Vendor hand-eye calibration
Files: `AutoCalibProccess.py`, `utilfs/handToEyeCalibration.py`, `visualValidCalib.py`, docs `AutoCalibProccess_使用说明.md`, `标定.md`.
- Eye-to-hand: the camera is fixed (torso), the chessboard is held by the arm.
- Board: **8 × 11 inner corners, 10 mm squares** (`boardRowNums`, `boardCowNums`, `boardLength` in `conf/userCmdControl.json`).
- `python AutoCalibProccess.py`: **k** saves an image + the arm TCP pose (kept only when corners are found); collect 15–20 poses with different positions and angles; **p** computes, **q** quits.
- Inside: `cv2.calibrateCamera` → `cv2.solvePnP` per image → `cv2.calibrateHandEye`; quality = position RMS error.
- Output: `conf/{project}_CalibParams.json` (+ images and `{project}_robotTcpPos.txt`).
- Check: `python visualValidCalib.py`, click a pixel, it prints the point in the arm base frame.
---
## 6. Vendor vision demos
All in https://github.com/JAKARobotics/jaka-robot-demos/tree/dev/jamie (copies in JAKA_Lumi `main` / `feat_ros`).
| Demo | What it does | Platform | Detector |
|---|---|---|---|
| LUMI_DEMO-v1 | Fixed-station pick: detect object + target, pick, place | x86_64 PC | Alibaba Qwen-VL (DashScope API) |
| LUMI_DEMO-v2 | Multi-station: AGV marker per station, body + arm home per station, pick/place | x86_64 PC | Qwen-VL |
| LUMI_DEMO-v3 | Voice wake-up ("lumi") + NanoOWL zero-shot detection + QR scan + AGV + arm (medicine picking) | Jetson Orin (ARM64), Docker | NanoOWL (OWL-ViT, TensorRT) / Qwen-VL |
| BMW vending demo | Voice agent sells drinks: fixed joint-space picks | Linux PC | — |
### v1 / v2 setup
```bash
pip install -r requirements.txt # opencv-python, numpy, matplotlib, dashscope, ...
export DASHSCOPE_API_KEY="..." # https://dashscope.console.aliyun.com/apiKey
export LD_LIBRARY_PATH=/path/to/JAKA_SDK_LINUX:$LD_LIBRARY_PATH
python AutoCalibProccess.py # once, or reuse the provided torso calibration
python visualDetect_ali.py # v1 (add --auto, --camera-sn SN, --list-cameras in v2)
python multi_station_demo.py # v2
```
`conf/userCmdControl.json` (v1): `cameraParams` (align SW, sync, image path), `objects.moveObjects` (e.g. "yellow doll") and `objects.putObject` ("box"), `robotParams.basePose` (start joints, rad), `relativeUpMotionHeight` (mm), offsets X/Y/Z/Zput (mm), `calibrateParams` (robot IP, board), `genNearPointParams`. v2 adds `operationMode` (`both` / `grasp_only` / `put_only` / `grasp_priority`), `systemConfig` (robot, AGV, body URLs), `extAxisLimits`, `stations` (name, AGV marker, arm home, body home, mode).
Vendor prompt to the VLM (translated): "Please box the N kinds of objects A and B in the image." Reply: JSON list of `{"label": ..., "bbox_2d": [x1, y1, x2, y2]}`. Then: box centre → depth → `pixel_to_world` → IK → pick.
### v3 (Jetson, Docker)
- Compose: image `lumi-demo-owl:v5audio`, `runtime: nvidia`, `network_mode: host`, `privileged: true`, devices `/dev/snd`, `/dev/bus/usb` (v3 compose also `/dev/video*`, `/dev/media*`, udev rules), volume `./lumi_nanoowl:/opt/nanoowl`, `DISPLAY` for GUI.
- Run: `./docker-compose-linux-aarch64 up --no-recreate -d`, then inside: `export LD_LIBRARY_PATH=/opt/nanoowl/JAKA_SDK_ARM:$LD_LIBRARY_PATH`, `python3 start_voice_wakeup_system.py --mode full` (or `owl`, `test`).
- Detector: `python3 lumi_demo_owl.py /opt/nanoowl/data/owl_image_encoder_patch32.engine --camera-sn <SN...>` (web UI on port 7860), or `lumi_demo_ali.py --camera-sn <SN>`.
- `FileExistsError: /root/.cache/clip` → `rm /root/.cache/clip && mkdir -p /root/.cache/clip`.
- Config `conf/voice_wakeup_config.json`: wake word, AGV IP/port and marker names, camera serials for QR scan and detection, robot IP.
---
## 7. Scene understanding (`vision/scene.py`)
What the cameras see, as facts for the conversation and the skills. It reads the camera service's files (raw JPEG, aligned depth, people and objects with arm-frame positions from `vision/objects.py`) and runs a pose model on the raw frame.
| Function | Gives |
|---|---|
| `sees(name, colour)` | things of a COCO class / colour in either camera: distance, bearing, "on my left / right / in front of me", `position_mm` (arm base frame); a thing seen by both cameras is reported once |
| `people()` | everyone in view, both cameras merged (the two cameras see a near person ~atan(0.25 m / d) apart) |
| `person_in_front()` | the nearest person within 3 m: distance, bearing, chest `position_mm`, facing, gesture (`hand_raised` / `pointing`), shirt and trousers colour, `hands: {left, right: {position_mm, object}}` |
| `object_in_hand()`, `person_holds(name)` | what is in a hand: `{name, colour, hand, position_mm, distance_m, width_mm}`; True / False / None (can't tell) |
| `pointing_target()` | first depth point along shoulder → wrist past the hand, `position_mm` |
| `ask_vlm(question)` | one sentence from `gemma4:26b` on the picture of the person (glasses, hat...) |
- **Pose**: YOLO11s-pose, 17 COCO keypoints, TensorRT engine `models/yolo11s-pose.engine` (`vision/pose.py`), 16–19 ms per 1280 × 720 frame on the GPU.
- **In the hand**: the frame's object boxes plus a second YOLOv8s pass on a 320 px square around each hand (wrist + 0.35 × forearm). A box counts when it is a handheld class, within the hand region, and its depth is within 0.35 m of the wrist's. Without usable depth the box centre must be on the hand.
- **Depth timing**: depth is written every 0.5 s, people and the JPEG every frame. When the depth at a person differs from the camera service's distance by more than 0.4 m, that frame's depth is not used (positions None, no "empty hand" claim).
- **Own body**: the robot's own body appears at the bottom edge of the head camera and the top edge of the torso camera (arm, held object). Boxes touching that edge nearer than 0.8 m (or unmeasured) are ignored.
- **Speed**: `person_in_front()` 50–60 ms with the models loaded (first call ~0.8 s; `seeing.warm_up()` loads them when the assistant starts). `snapshot()` 20 ms.
- **VLM**: `gemma4:26b` with a 448 px picture, about 5 s on an idle GPU, longer while other LLM work runs. Used only for what detections can't answer; time limit 12 s, then "I can't tell".
- **Test frames**: `tests/data/scene_*`; `python vision/scene.py --save tests/data/<name>` saves the current frames. Check: `tests/test_scene.py`.
+108
View File
@@ -0,0 +1,108 @@
# 07. Voice and audio
The microphone array, the speaker, Lumi's speech pipeline, sound direction, and the vendor voice demo. The pipeline runs on the Jetson Thor: [08_NVIDIA_THOR.md](08_NVIDIA_THOR.md).
---
## 1. Hardware
| Item | Value |
|---|---|
| Microphone module | iFlytek AIUI XF-USB-MC, 6-mic ring array in the head |
| Device name | USB audio device **`AIUI-USB-MC`** ("AIUI-USB-MC: USB Audio"), ALSA `hw:CARD=AIUIUSBMC`; older name in vendor code: `XFM-DP-V0.0.18` |
| Channels | 8 at 16 kHz: channels 0–5 are the six ring mics, 6–7 are silent |
| Connection | USB, through the base's USB 3.0 port shared with the cameras |
| SNR | > 70 dB |
| Wake / recognition distance | 3–5 m (spec); an external mic extends the range |
| Sound source localisation (spec) | 6 mics: 360°, ±15°; 4 mics: 180° |
| Speaker | USB device "USB Audio Device", ALSA `plughw:CARD=Device,DEV=0` |
| Clip microphone (optional) | wireless DJI Mic Mini; its receiver appears as a sound card |
List devices: `arecord -l` / `aplay -l`. In Docker pass `/dev/snd` and add the `audio` group.
---
## 2. Lumi's speech pipeline
| Stage | Module | Implementation |
|---|---|---|
| Recording | `audio/mic.py` | One always-on recording; an ALSA device opens only once, so everything that listens goes through it. An energy detector cuts utterances. Source chosen in `data/mic_source.txt`: `auto` / `head` / `clip` |
| Voice activity | `audio/ears.py` | Silero VAD 5.1.2 (ONNX Runtime): sounds without enough speech frames (music, noise) never reach speech-to-text |
| Speech-to-text | `audio/ears.py` | whisper.cpp 1.9.5 (CUDA) server with `large-v3-turbo` (f16) on `127.0.0.1:8096`, started when needed; English, Korean and mixed speech |
| Sound direction | `audio/doa.py` | SRP-PHAT over the six ring mics (§3) |
| Text-to-speech | `audio/mouth.py`, `audio/tts_gpu.py` | Supertonic 3 (English and Korean, voice `F1`), vector estimator and vocoder as TensorRT engines on the GPU; CPU (ONNX Runtime) when the engines are not loaded |
Behaviour:
- With a clip mic connected, utterances and their text come from the clip mic; the head array keeps recording in parallel for the sound direction.
- While Lumi speaks the head array records nothing. The clip mic keeps listening, so the visitor can interrupt ("stop", a new question); Lumi's own voice in the clip mic is recognised by comparing it with what the speaker played (`mouth.own_voice`) and dropped.
- Long answers are split into sentences; the next sentence is synthesised while the current one plays. Fixed phrases (greetings) are synthesised once and cached.
- Volume and speaking speed are kept in `data/volume.txt` and `data/speech_speed.txt` (voice commands and the dashboard).
Commands:
```bash
.venv/bin/python audio/mic.py # print every utterance: source, length, level, direction
.venv/bin/python audio/ears.py # listen once, print the text
.venv/bin/python audio/mouth.py "Hello, I am Lumi." # speak
.venv/bin/python audio/tts_gpu.py build # build the TTS engines (after a JetPack / TensorRT change), then: check
```
Tunable values: [TUNING.md](TUNING.md#voice).
---
## 3. Sound direction
The vendor code only records audio; it does not read a direction-of-arrival angle from the module. Lumi computes the direction itself from the six ring channels (`audio/doa.py`):
- SRP-PHAT: for each candidate direction (2° grid, −180…180°) the expected time differences between the mic pairs are compared with the PHAT-weighted cross-spectra (300–3500 Hz); the direction with the most energy wins.
- Angles are in the head frame: 0 = where the head looks, + = to the robot's left (same sign as head yaw). Robot (waist) angle = head yaw + this angle.
- Geometry: six mics on a ring of `radius`, mic k at `offset + sign · k · 60°`, kept in `data/doa_calib.json`.
- Calibration needs a speaker at known angles. `assistant/lumi.py` collects samples on its own while it talks with a person the head camera sees (camera angle = truth) and fits sign / offset / radius after 6 samples spread over at least 30°. By hand: `python audio/doa.py --calibrate` (stand in front of the head camera, talk, move left and right, Ctrl+C to fit).
---
## 4. Recording audio (vendor method)
The vendor demo (LUMI_DEMO-v3 `services/voice_recognition_service.py`, `audio_tool/audio_tools.py`) uses the module as a normal microphone: PyAudio, **16 kHz, mono, 16-bit, chunks of 1024**, device chosen by name.
```python
import pyaudio, wave
def find_input(name="AIUI-USB-MC"):
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
info = p.get_device_info_by_index(i)
if info["maxInputChannels"] > 0 and name in info["name"]:
return i
return p.get_default_input_device_info()["index"]
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True,
input_device_index=find_input(), frames_per_buffer=1024)
frames = [stream.read(1024, exception_on_overflow=False) for _ in range(int(16000 / 1024 * 5))] # 5 s
stream.close()
with wave.open("test.wav", "wb") as wf:
wf.setnchannels(1); wf.setsampwidth(2); wf.setframerate(16000); wf.writeframes(b"".join(frames))
```
Vendor device list: `python3 audio_tool/test_audio_devices.py`. On Lumi the recording belongs to `audio/mic.py`; stop the assistant before opening the device from another program.
---
## 5. Vendor voice demo (LUMI_DEMO-v3)
| Part | Implementation |
|---|---|
| Wake word | "lumi" (config `voice_recognition.wakeup_word`), timeout 10 s, record 5 s |
| Speech-to-text | OpenAI Whisper, local (`whisper_main`, model `base.pt`) |
| Text-to-speech | iFlytek online TTS (WebSocket `wss://tts-api.xfyun.cn/v2/tts`, 16 kHz raw, voices `x4_yezi` / `aisjinger`; needs an APPID / APIKey / APISecret) or MeloTTS offline (zh, en, ja, ko, …; CPU real-time) |
| Tasks | QR scan, NanoOWL detection, AGV markers (`table`, `shelf`, `home`), arm picking |
| Start | `python3 start_voice_wakeup_system.py --mode full` inside the Docker container |
---
## 6. Company voice assistant
The company runs its own Lumi voice assistant on the Jetson Thor, separate from this project. Its behaviour, architecture and endpoints are company-internal and documented in `docs/private/` (not in git).
+148
View File
@@ -0,0 +1,148 @@
# 08. NVIDIA Jetson AGX Thor
Main AI computer of Lumi: runs the robot software, vision models, speech and the LLM. Address and login: `docs/private/ACCESS.md` (not in git).
---
## 1. Specifications
| Item | Value |
|---|---|
| Model | NVIDIA Jetson AGX Thor Developer Kit |
| Compute | 2070 TOPS (INT8), Blackwell GPU (1.57 GHz), 72-core Arm v9 CPU (2.6 GHz) |
| Memory | up to 128 GB unified |
| Storage | PCIe 5.0 NVMe + UFS 4.0 |
| Power | 30–120 W (configurable) |
| Current JetPack release | JetPack 7.2.1, Jetson Linux r39.2.1 |
| Ports | 2 × USB-C (power/data), USB-A, HDMI/DisplayPort, Ethernet, Debug-USB behind the lid |
JAKA's computer options table ([01_HARDWARE.md](01_HARDWARE.md)) puts large multimodal models (≥ 30B, VLA, ACT, LLM + vision) on the AGX Thor.
### This unit
| Item | Value |
|---|---|
| Hostname | `lumi-thor` |
| Software | JetPack R38.4, CUDA 13.0, driver 580, Ubuntu 24.04, Python 3.12 |
| CPU / memory | 14 cores (aarch64), 122 GB shared by CPU and GPU |
| Network | robot LAN `enP2p1s0` (192.168.10.240); internet over its own Wi-Fi `wlP1p1s0` |
---
## 2. Connect
SSH from a computer on the same network: `ssh <user>@<thor-ip>`, port 22 (`ssh -X` for GUI programs such as OrbbecViewer or RViz). On the robot network (`192.168.10.x`) the Thor's address is also listed on the router page `http://192.168.10.79` (connected devices) or found with `nmap -sn 192.168.10.0/24`. Network details: [02_NETWORK_AND_ACCESS.md](02_NETWORK_AND_ACCESS.md).
---
## 3. Install the OS (re-flash)
NVIDIA quick start: https://docs.nvidia.com/jetson/agx-thor-devkit/user-guide/latest/quick_start.html
Requirements: a PC with 25 GB free, a USB stick ≥ 16 GB, a monitor + keyboard (or a USB-C cable for headless setup).
1. Download the installer ISO (e.g. `jetsoninstaller-r39.2.1-...-arm64.iso`) from NVIDIA Developer Downloads.
2. Write it with **Balena Etcher** (https://etcher.balena.io). Copying the file to the stick does not work.
3. Plug the stick into the Thor (USB-A or USB-C), connect the bundled USB-C power supply, press the power button (left button on the side).
4. Boot from USB: Enter (or wait); accept the **QSPI capsule update** with **Y** (do not skip); installation to NVMe takes about 10 minutes, then it reboots.
5. **Remove the USB stick** right away.
6. First-boot wizard (oem-config): keyboard, licence, network, time zone, user name and password, hostname. Headless: connect the USB-C cable to a PC, open a serial terminal, press Tab then Enter.
7. Use the bundled power supply; avoid KVM switches. Factory UEFI 38.0.0 has display issues in headless mode (NVIDIA documents a workaround); devices reinstalled with a pre-7.2 ISO may need UEFI changes.
8. Then install the JetPack components and CUDA (NVIDIA pages "JetPack SDK Setup", "CUDA Setup").
---
## 4. Docker
NVIDIA's procedure (https://docs.nvidia.com/jetson/agx-thor-devkit/user-guide/latest/setup_docker.html), also when `docker compose` does not work on a fresh system:
```bash
sudo apt-get update
sudo apt install -y nvidia-container curl
curl https://get.docker.com | sh && sudo systemctl --now enable docker
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl daemon-reload && sudo systemctl restart docker
# make nvidia the default runtime
sudo apt install -y jq
sudo jq '. + {"default-runtime": "nvidia"}' /etc/docker/daemon.json | sudo tee /etc/docker/daemon.json.tmp \
&& sudo mv /etc/docker/daemon.json.tmp /etc/docker/daemon.json
# run docker without sudo
sudo usermod -aG docker $USER && newgrp docker && sudo systemctl restart docker
# check: compose and GPU
docker compose version
docker run --rm -it nvcr.io/nvidia/pytorch:25.08-py3 python3 -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))"
```
`/etc/docker/daemon.json` contains `"runtimes": {"nvidia": {"path": "nvidia-container-runtime", "args": []}}` and `"default-runtime": "nvidia"`.
---
## 5. Software on the Thor
- **Lumi**: the user systemd service `lumi-api` runs `api/server.py` (API and dashboard on `:8100`); the API starts the camera service, whisper, the embedding server and loads the LLM. `systemctl --user restart lumi-api` restarts it. See the top-level README.
- **On the GPU**: Ollama (`gemma4:26b`, Lumi's LLM), whisper.cpp (CUDA), the bge-m3 embedding server, the camera service's YOLO, the pose model and the Supertonic TTS engines.
- **Company voice services**: containers of the company's own voice assistant; installation and layout in `docs/private/` (not in git). They need about 80 GB of GPU memory; leave room for vision models.
- **Colleagues' projects** on this Thor are separate: `~/Dev/lumi_edu`, `lumi-vision`, `lumi_voice_app`, services on :8000, :8001, :8090, :3080.
### Vendor SDKs
- The JAKA SDK has an `aarch64-linux-gnu` build of `jkrc`; check that `jkrc.so` loads under Python 3.12, otherwise use a Python 3.10 container. The `jkrc.so` installed here is x86-only; Lumi drives the arm through the controller's JSON port (`robot/arm.py`, `robot/gripper.py`).
- Orbbec SDK: arm64 `.deb` packages and the vendor's Jetson Docker setup ([06](06_CAMERAS_AND_VISION.md#v3-jetson-docker)).
- In containers, mount the code (`-v $PWD:/work`), as the vendor compose files do.
---
## 6. GPU inference
- **TensorRT** 11.4 from pip (`tensorrt-cu13`, with `cuda-python`) runs on this GPU. TensorRT 11 has no FP16 builder flag (networks are strongly typed). An engine runs only with the TensorRT version and GPU it was built with: rebuild every engine after a JetPack or TensorRT change.
- **onnxruntime-gpu** 1.31 (pip) lists the CUDA provider, but its kernels do not run on this GPU ("no kernel image is available for execution on the device"). Use TensorRT for GPU inference.
- Detector speed: YOLOv8s engine 2.5–4 ms, YOLOv8n engine 4 ms per 640 frame; YOLOv8n on the CPU (OpenCV DNN) ~45 ms. The camera service uses ~1 CPU core with the detector on the GPU, ~8.4 cores with it on the CPU.
- OpenCV 5.0 in the venv has no `cv2.calibrateHandEye` (`vision/calib.py` has its own solver). The system Python has no OpenCV: run modules with `.venv/bin/python`.
---
## 7. Models and local files
Not in git; made on the Thor.
| Path | What | How it is made |
|---|---|---|
| `.venv/` | Python 3.12 venv; `site-packages/lumi_wave.pth` puts the project folder on the path. numpy, opencv-python-headless, pyorbbecsdk2, fastapi, uvicorn, supertonic, soundfile, tensorrt-cu13, cuda-python | top-level README |
| `models/yolov8s.onnx`, `models/yolov8s.engine` | GPU detector | `YOLO("yolov8s.pt").export(format="onnx", imgsz=640, opset=17)`; `vision/yolo_engine.py models/yolov8s.onnx models/yolov8s.engine` (~100 s) |
| `models/yolov8n.onnx` | CPU fallback detector | `YOLO("yolov8n.pt").export(format="onnx", imgsz=640, opset=12, simplify=True)` |
| `models/yolo11s-pose.onnx`, `.engine` | pose keypoints for `vision/pose.py` | ultralytics 8.4 export (imgsz 640), then `vision/yolo_engine.py` |
| `models/face_detection_yunet_2023mar.onnx`, `models/face_recognition_sface_2021dec.onnx` | face detector and embedding for `vision/reid.py` (without them only clothes are used) | github.com/opencv/opencv_zoo |
| `models/ggml-large-v3-turbo.bin` | whisper model (f16); `ggml-large-v3-turbo-q5_0.bin` is used by `audio/sing_mine.py` | Hugging Face `ggerganov/whisper.cpp` |
| `models/supertonic3/` | TTS model | Hugging Face `Supertone/supertonic-3` |
| `models/supertonic3_vector_estimator.engine`, `models/supertonic3_vocoder.engine` | TTS vector estimator and vocoder on the GPU (`audio/tts_gpu.py`); without them the CPU, 5–10× slower | `.venv/bin/python audio/tts_gpu.py build`, then `check` |
| `whisper.cpp/` | v1.9.5 with CUDA | `cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=110 -DCMAKE_BUILD_TYPE=Release && cmake --build build -j 12 --target whisper-server whisper-cli` |
| `~/models/bge-m3-Q8_0.gguf` | embedding model for the knowledge base | Hugging Face |
| `knowledge/index.npz` | knowledge vectors | `assistant/knowledge.py build` |
| Ollama `gemma4:26b` | LLM | `ollama pull gemma4:26b` |
| `data/camera_extrinsics*.json`, `data/calib_samples*/`, `data/doa_*`, `data/volume.txt`, `data/speech_speed.txt` | calibrations and settings of this robot | `vision/calib.py`, `audio/doa.py`, the dashboard |
| `logs/` | log files and debug pictures | written at run time |
| `docs/private/` | company-internal notes (access, vendor manuals, screenshots) | kept off git |
The Orbbec cameras need the udev rule `SUBSYSTEM=="usb", ATTR{idVendor}=="2bc5", MODE="0666"` in `/etc/udev/rules.d/99-orbbec.rules`.
---
## 8. Operating rules
- Only the camera service opens the cameras ([06](06_CAMERAS_AND_VISION.md#3-camera-service-visioncamviewpy)). After `vision/camview.py --stop` / `--start` the torso camera may take a few seconds to re-enumerate: wait and start again.
- After any cable work, check the camera link speed (`/sys/bus/usb/devices/*/speed` = 5000); a camera opened at USB 2 stays colour-only until the camera service is restarted.
- Do not restart the API while the base drives: check `curl -s localhost:8100/status` → `base.move_status` first.
- Never call `tasks/fetch.py` functions from a second process while the API runs: its log writes that process's empty state over `/dev/shm/lumi_task.json`.
- Tests never reach the robot (`tests/test_*.py` fake the hardware).
- After a controller power cycle the body axes are disabled; `robot/head.py` `moveto()` enables them. All tool I/O must be PNP in Cobo π.
- The body API's `/stop` does not stop a `moveto`; hold-to-move uses small steps.
- Navigation does not go into a table's margin (such a goal ends "succeeded" without moving); a reach ends with a straight checked drive. Drives run with the arm in `look`, not `carry` (the base's 3D camera sees the hand in `carry` and stalls).
- The base's planning API does not check real paths; `robot/nav.py` uses the map image. Closed glass doors need a no-go line in the base's web panel.
- `pkill -f` / `pgrep -f` also match your own shell's command line: find the PID with `ps -eo pid,args | grep "[n]ame"` and kill that.
- Headless Chrome screenshots of the dashboard: do not use `--timeout` (it freezes the page's JavaScript).
- Do not touch colleagues' projects and services (§5).
Every value meant to be tuned by hand, with its file: [TUNING.md](TUNING.md).
+154
View File
@@ -0,0 +1,154 @@
# 09. ROS 2, teleoperation, learning and simulators
Vendor software beyond the plain APIs: the ROS 2 workspace with MoveIt 2 and Isaac Sim, VR teleoperation, ACT imitation learning.
---
## 1. ROS 2 workspace `jaka_lumi_ros` (MoveIt 2, Isaac Sim)
Source: JAKA_Lumi repo, branch **`feat_ros`**, folder `jaka_lumi_ros/` (ROS 2 **Humble**, Ubuntu 22.04).
```bash
git clone -b feat_ros https://github.com/JAKARobotics/JAKA_Lumi.git # large repo; or sparse-checkout jaka_lumi_ros
cd JAKA_Lumi/jaka_lumi_ros
source /opt/ros/humble/setup.bash
colcon build --symlink-install
source install/setup.bash
```
| Package | Role |
|---|---|
| `jaka_lumi_body_node` | Topics/services for the body over HTTP (`/joint_states`, `/lumi_body/enable|move|stop|reset|read_status`), details in [03](03_BODY_LIFT_WAIST_HEAD.md#4-ros-2) |
| `jaka_lumi_body_server` | `FollowJointTrajectory` action server for the body; publishes the TF root (start it first) |
| `jaka_lumi_minicobo_arm_server` | `FollowJointTrajectory` action server for the arm via JAKA SDK (`servo_j`, 8 ms steps, joint LPF 0.5); parameter `ip` (default `192.168.10.90`); powers on and enables the arm at start; publishes `/joint_states` `l_a1…l_a6` |
| `jaka_lumi_description` | URDF, meshes, USD files, RViz config |
| `jaka_lumi_moveit_config` | MoveIt 2: groups `jaka_lumi_body` (l_1…l_4), `jaka_lumi_minicobo_arm` (l_a1…l_a6), `jaka_lumi_full_robot`; default velocity/acceleration scaling 0.1; max joint velocity 1.57 rad/s; states `zero`, `pose_1` |
| `jaka_lumi_isaacsim` | Launch Isaac Sim with the Lumi USD; topics `/isaac_joint_states`, `/isaac_joint_commands` |
Run on the real robot:
```bash
ros2 launch jaka_lumi_body_server lumi_body_server.launch.py # always first
ros2 launch jaka_lumi_minicobo_arm_server lumi_minicobo_arm_server.launch.py ip:=192.168.10.90
ros2 launch jaka_lumi_moveit_config demo.launch.py # RViz + MoveIt 2
```
Body only: body server + `demo.launch.py`. Standalone body node: `ros2 launch jaka_lumi_body_node lumi_body_node.launch.py`.
Controllers (only one owner per joint):
```bash
ros2 control switch_controllers --activate jaka_lumi_full_robot_controller \
--deactivate jaka_lumi_body_controller jaka_lumi_minicobo_arm_controller --strict
ros2 control switch_controllers --activate jaka_lumi_body_controller jaka_lumi_minicobo_arm_controller \
--deactivate jaka_lumi_full_robot_controller --strict
```
Simulation modes (replace MoveIt's `launches.py` with the one in `jaka_lumi_ros`; find it with `find /opt/ros/humble/ -name launches.py`):
```bash
ros2 launch jaka_lumi_moveit_config demo.launch.py use_rviz_sim:=true # fake controllers
ros2 launch jaka_lumi_isaacsim run_lumi_isaacsim.launch.py # Isaac Sim 4.5 + Lumi USD
ros2 launch jaka_lumi_moveit_config demo.launch.py use_isaac_sim:=true
```
Isaac Sim install: https://docs.isaacsim.omniverse.nvidia.com/4.5.0/installation/install_workstation.html. If it segfaults: `rm -rf ~/.nvidia-omniverse/logs ~/.nvidia-omniverse/config`; test without ROS: `cd jaka_lumi_isaacsim/scripts && ./python.sh isaacsim_moveit.py`; fallback: `ros2 launch jaka_lumi_isaacsim run_isaacsim.launch.py`, then File → Open `jaka_lumi_description/urdf/jaka_lumi/jaka_lumi_moveit.usd`, Play.
Servo mode note: the arm server needs servo mode, which controller 3.2 does not support yet ([04](04_ARM.md#2-controller-versions-17-vs-32)).
---
## 2. VR teleoperation (PICO 4)
Sources: JAKA web doc 3.2.3, teleop quick-start docx, JAKA_Lumi branch **`LumiCode`** (`Lumi_Teleoperation/`).
**Only controller 1.7 (1.7.1-46-X64-minicab) is supported; controller 3.2 is not.**
| Part | Form | Role |
|---|---|---|
| VR sender | Android app on the PICO 4 (Ultra) | Sends controller poses and buttons |
| VR receiver | Docker container on an Ubuntu PC (ROS 2 Humble) | Converts them into robot Cartesian targets |
| Robot controller side | same container | Cartesian servo (`servo_p`) to the arm |
Network: VR headset and PC on the same Wi-Fi (Lumi's own Wi-Fi recommended, 5 GHz for low latency); PC also reaches the robot.
### PICO setup
1. On the headset: Control Center → Settings → About → tap the software version several times → Developer options → **USB debugging** on.
2. On the PC: install PICO Developer Center (https://developer-cn.picoxr.com/resources/#pdc). PICO docs: https://developer-cn.picoxr.com/document/unity/set-up-the-development-environment/
3. USB-cable the headset to the PC, unzip `controlData_*.zip`, copy the APK to *PICO 4 Ultra → internal shared storage → Download*.
4. In the headset: File manager → Installation packages → install. It appears under Library → **Unknown sources** (apps `controllers_data_250220`, `robotB612`, `imgVR_250220`; use the one with the yellow smiley icon).
5. Open it, enter: **PC IP** (`ifconfig` on the PC, e.g. `192.168.10.35`), **PC port** (doc default 8018; the Lumi launch file uses **9852**; they must match), **send period** 0.01 s (60 Hz) → **LOGIN**. Move the controllers and check the virtual hands follow; if laggy, check both are on the same Wi-Fi.
### PC setup
```bash
# Docker (or the fishros helper: wget http://fishros.com/install -O fishros && . fishros)
docker load -i jaka_images_lumi_v1.0.tar.gz # image jaka_images:lumi_V1.0 (≈ 37 GB on disk); from a JAKA engineer
docker images -a
# plug grippers / cameras first (cameras USB 3.0, grippers USB 2.0); ls /dev/ttyUSB* ; lsusb
docker run -it --name lumi_yao --net=host --ipc=host --pid=host \
--device=/dev/bus/usb:/dev/bus/usb --device=/dev/usb:/dev/usb \
-v /home/$USER/data:/home/data -v /dev/shm:/dev/shm \
-d jaka_images:lumi_V1.0
# (add --device=/dev/ttyUSB0 --device=/dev/ttyUSB1 for grippers)
docker start lumi_yao
docker exec -it lumi_yao bash
vim ~/Lumi_Teleoperation/src/vr_data_pub/launch/teleoperation_system_lumi.launch.py # set robot_ip (and server_port)
colcon build && source ~/.bashrc
ros2 launch vr_data_pub teleoperation_system_lumi.launch.py # terminal 1: communication + robot init (power on, enable)
ros2 run vr_data_pub teleoperation_control_lumi # terminal 2: control state machine
```
In the vendor launch file: `vr_data_pub` (socket server, `server_port: 9852`), `vr_data_distributer`, `k1_robot/robot_interface` (namespace `/right_arm`, `robot_ip`, `robot_running_mode`: `teleop` / `act` / `test`), `vr_robot_pose_converter_lumi_servo_p`.
### Controller buttons
| Button | Action |
|---|---|
| Either side (grip) button | Start controlling the arm (be ready: the arm follows immediately) |
| B | Pause and return to the default pose; **disabled by default** (enable and set the home in `move_to_default_pose` of `teleoperation_control_lumi.py`). Lumi default: rad `[0.3183, -1.4058, -0.8646, -0.2966, -1.3689, 0]` |
| Y | Stop control and exit; rerun `ros2 run vr_data_pub teleoperation_control_lumi` to resume |
| X | Start recording data (data collection mode) |
| A | Save the recorded episode and stop recording |
Data collection: put the camera serials into `OrbbecSDK_ROS2/orbbec_camera/launch/multi_gemini2L_synced_sn_template.launch.py`, `colcon build`, `ros2 launch orbbec_camera multi_gemini2L_synced_sn_template.launch.py`, then `ros2 run vr_data_pub collect_data_xy` (Lumi version: `aloha_data_prepare_lumi.py`).
Safety: physical E-stop within reach; move slowly at first; if the robot shakes, press the E-stop; if communication drops, check the Wi-Fi. Troubleshooting: Docker fails to start → `sudo chmod 666 /dev/ttyUSB*`.
VM setup (from the docx): two network adapters, one bridged to the wired port (robot, `10.5.5.x` in the docx), one bridged to Wi-Fi (headset); if networking fails, swap `ens33` / `ens37`.
---
## 3. Imitation learning (ACT, Mobile ALOHA)
- Code: JAKA_Lumi `LumiCode` branch `Lumi_Training/` (fork of the ACT / Mobile ALOHA repo: `imitate_episodes.py`, `policy.py`, `detr/`, `constants.py`), Google Drive link in the repo.
- Install (docx "Docker ACT"): Docker + NVIDIA Container Toolkit; image `actimages:V1.0` (environment only, mount the code) or V1.1 (code in `/ACT`); compose:
```yaml
services:
act:
image: actimages:V1.0
container_name: act
volumes: ["../ACT:/ACT", "/dev/shm:/dev/shm"]
network_mode: host
command: /bin/bash -c "sleep infinity"
runtime: nvidia
environment: [NVIDIA_VISIBLE_DEVICES=all]
```
- `docker compose -f docker-compose.act.yml up -d`, enter the container, set `DATA_DIR` and the camera names in `/ACT/constants.py` (same names as in the dataset; example cameras `front_cam`, `right_cam`, action dim 7, chunk 25), create a checkpoint folder, comment out wandb in `train.py`, run `train.py`.
- ACT tuning tips: train long (≥ 5000 epochs on real data); jerky policies improve with more training.
- `Lumi_Training/JAKASDK/` scripts are for a 7-DOF dual-arm robot (K1): useful only as examples of SDK ↔ MuJoCo transforms.
---
## 4. Simulators summary
| Simulator | Where | Status |
|---|---|---|
| RViz fake controllers | `jaka_lumi_moveit_config use_rviz_sim:=true` | vendor |
| Isaac Sim 4.5 | `jaka_lumi_isaacsim` | vendor |
| Cobo π / JAKA App simulation switch | controller hardware-in-the-loop | arm only |
| JAKASim virtual machine | "About the Development" on jaka.com, used with the App's offline connection | arm only |
+135
View File
@@ -0,0 +1,135 @@
# 10. Gripper
A Zimmer electric parallel gripper is mounted on the arm flange. It is driven by the two digital outputs of the arm's tool connector and reports its finger position on an analog input. An optical sensor on one finger mount detects objects below the gripper.
---
## 1. Hardware
| Part | Description |
|---|---|
| Gripper | **Zimmer GEP2013IO-05-B**: electric 2-jaw parallel gripper, digital I/O version. GEP2013 family datasheet: **13 mm stroke per jaw**, **gripping force 90–360 N** in four levels, **mass about 0.54 kg** without fingers. Rotary switch "Funct" 1–4 selects the force level (4 = 360 N); set to **1**. Green LED = powered |
| Fingers | Long stainless-steel fingers with curved tips on L-shaped brackets, for cups and glasses. Fingertips about 265 mm from the flange face; the fingers sit beside the flange axis, not on it (about 8 cm off, estimate) |
| Finger sensor | **MISUMI** optical (photoelectric) sensor, yellow/black housing, on the side of one finger mount. It sees what is **below the gripper**, not an object between the fingers. The red light is its emitter and is always on; the indicator LED on its back is red when something is in front of it, blue when nothing is |
| Cable | Gripper and sensor are wired to the arm's M8 tool connector (TIO), see [04_ARM.md §8](04_ARM.md#8-tool-io-connector-m8-8-pin-tio-v3) |
Even force level 1 (~90 N) is far more than a plastic cup needs: the software must not close on objects that cannot take it (`manipulation/skills.py` refuses objects of the wrong width).
### Finger geometry
Each finger is a straight thin shank below its mount block, then a C-shaped hook that bends out and curves back in to an inward tip. Inner gap between the fingers:
| Where | Open | Closed |
|---|---|---|
| Tips (entry gap) | 88 mm | 59 mm |
| Belly: widest point inside the hook | 96 mm | 70 mm |
| Neck: narrowest point where the hook meets the shank | 73 mm | 47 mm |
| Shank: the straight part, same gap along its length | 66 mm | 39 mm |
Along the fingers, from the bottom face of the Zimmer body (±5 mm): shank starts ~100 mm, hook starts ~150 mm, tips ~200 mm.
A round object narrower than 70 mm is not squeezed by the belly. An 82 mm cup passes the 88 mm entry with only ~3 mm per side: approach on the centre line.
**Grasp point** (where a cup's axis sits between the fingers, 4 cm below the rim): **(106.4, −86.5, 230.5) mm in the flange frame** (268 mm from the flange, 137 mm off its axis), stored in `data/grasp_teach.json` with the flange pose.
---
## 2. Signals
**All tool I/O must be set to PNP** (Cobo π → I/O → Tool(S), ⋮ menu of each DI / DO → PNP). With the factory setting NPN the gripper does not move and the sensor is not read.
| Signal | Direction | Meaning | Values |
|---|---|---|---|
| **DO_1** | controller → gripper | **Close** | 1 = close |
| **DO_2** | controller → gripper | **Open** | 1 = open |
| **AI_1** | gripper → controller | **Finger position** (0–10 V, read as 0–4096) | 100–160 open · 4100–4200 closed on nothing (noise ±50) · in between while moving or holding |
| **DI_1** | sensor → controller | **Something below the gripper** | 1 = object, 0 = nothing; never set by an object held between the fingers |
| DI_2 | | not connected | always 0 |
| AI_2 | | not connected | ~489 (floating input) |
### AI_1 and the finger gap
The gap is linear in AI_1 between fully open and closed on nothing; `gripper.gap_mm(ai, where)` gives the width at the tips, belly, neck or shank, and `state()["gap_mm"]` is the belly gap. Plastic cups give a little, so their gap reads somewhat under their real diameter. The value right after closing overshoots: read it about 1 s after the close.
### Behaviour
- One stroke (open → closed or back) takes about **1 s**.
- **The fingers stay where they are when both outputs are off.** No signal is needed to keep holding.
- **Never switch both outputs on at the same time** (open and close together). Switch the other output off first.
- Closing on an object stops the fingers early and AI_1 stays lower (a cup's wide part: about 3500).
- Small or soft objects give no reliable reading: a thin plastic cup gripped at its narrow end gives way and reads like empty (~4150). Paper cups are squeezed flat and then read as empty.
- **A close cannot be stopped half way**: switching DO_1 off during the stroke does not stop the fingers. A gentler close from software is not possible with these outputs.
- The fingers have no touch sensing, and a pull on a held object does not change AI_1 beyond the settling noise: the gripper cannot detect a hand-over.
### PNP and NPN
- **PNP** ("sourcing"): the signal wire is connected to **+24 V** when the signal is on. Common on European equipment (Zimmer, Sick, Festo).
- **NPN** ("sinking"): the signal wire is connected to **0 V (ground)** when the signal is on. Common on Japanese and Chinese equipment.
Both ends of a signal must use the same type; otherwise nothing is read.
---
## 3. Software
`robot/gripper.py` drives the gripper through the arm controller's JSON command port (192.168.10.90:10001, no SDK):
```bash
python robot/gripper.py # {'closed': ..., 'holding': ..., 'object_in_front': ..., 'ai': [...], 'do': [...], 'di': [...]}
python robot/gripper.py open
python robot/gripper.py close
```
```python
from robot import gripper
gripper.state()["object_in_front"] # DI_1
gripper.close() # DO_2 off, DO_1 on, wait MOVE_S, return state()
gripper.state()["holding"] # closed and AI_1 below EMPTY_AI
gripper.open_()
```
| Constant | Value | Meaning |
|---|---|---|
| `CLOSE_DO`, `OPEN_DO` | 0, 1 | DO_1, DO_2 (0-based index) |
| `CLOSED_AI` | 400 | AI_1 above this = closed |
| `EMPTY_AI` | 3900 | closed and above this = nothing between the fingers |
| `GAP_MM` | see §1 | inner gap (open, closed) at tips, belly, neck, shank |
| `SENSOR_DI` | 0 | DI_1 |
| `MOVE_S` | 1.5 | s to wait for a stroke |
Raw command: `{"cmdName": "set_digital_output", "type": 1, "index": <0|1>, "value": <0|1>}` (type 1 = tool I/O). The state comes from `get_data` (`tio_dout`, `tio_din`, `tio_ain`).
The API exposes `GET /gripper/state`, `POST /gripper/open`, `POST /gripper/close` (open / close are refused with 409 while a task runs); the dashboard Arm tab has Open / Close buttons and the live state. During a hand-over Lumi opens only on "thank you" or the dashboard's Release.
---
## 4. Payload and TCP
Settings → Payload, slot **`zimmer_gripper`**, selected as the active payload:
| Field | Value | Basis |
|---|---|---|
| Load | **1.000 kg** | estimate: gripper 0.54 kg (datasheet) + steel fingers and brackets |
| Centre of mass | **X 30, Y 0, Z 80 mm** | estimate: fingers on the +X side of the flange, heavy body close to the flange |
"One-click Auto Identification" is not available: it returns error `0x0F0088` "Payload identification only be supported in floor-mounting", and the Lumi arm is side-mounted (Mounting Orientation Y 90°, do not change it). The payload is entered by hand.
The TCP offset is kept in the Lumi code (camera calibration and the grasp point), not in Cobo π.
The collision limits are at the loose defaults (force 100 %, TCP speed 5000 mm/s, momentum 10 kg·m/s, power 600 W, stop distance 4000 mm). Tighten them before the arm works near people, in small steps, checking that normal motions still pass.
---
## 5. Other gripper options on Lumi (vendor material)
JAKA's education kit uses a **DH Robotics DH-PGEA-50** with 3D-printed fingers, driven over **Modbus RTU (RS485)**. The tool connector's DO pins can be switched to RS485 channel 1 for this (Cobo π → I/O → Tool → DO_1 → "Reuse as RS485 channel 1"). Vendor settings: slave 1, 115200 baud, 8N1. Registers: `0x0100` initialise, `0x0101` force %, `0x0103` target position (0 closed … 1000 open), `0x0200` init state, `0x0201` grip state, `0x0202` position. The vendor demos also use a USB-RS485 adapter on the host (`/dev/DH_hand`) and DH AG-95 grippers through `pyDHgripper`. Sources: jaka-robot-demos `LUMI_DEMO-v3/.../dh_gripper.py`, JAKA_Lumi `LUMI_DEMO_BMW/LumiAgent/utilfs/python_open_gripper.py` (see [12_SOURCES.md](12_SOURCES.md)).
Arm-side limits for any gripper:
| Item | Value |
|---|---|
| Flange | ISO 9409-1, pitch circle 50 mm, 4 × M6, Ø6 H7 pin hole |
| Payload | 2 kg in total (gripper + object), less with a larger centre-of-mass offset |
| Tool power | 24 V or 12 V, 1 A continuous, 2 A peak |
| Tool DO | 2 × ≤ 1 A, NPN / PNP / push-pull |
| Tool AI | 2 × 0–10 V |
+48
View File
@@ -0,0 +1,48 @@
# 11. Safety
Rules for working with the real Lumi, collected from the Lumi manual, the Mini hardware manual, the JAKA App manual, the chassis manual and the vendor web doc. Read before the first power-on.
---
## 1. Stop devices
| Device | What it does | How to release |
|---|---|---|
| Red E-stop button on the column | Cuts arm power, stops the lift column; the base becomes free to push | Turn to release; then power on and enable the arm again. After release the base can no longer be pushed |
| E-stop on the chassis | Stops the base (LED flashes) | Release the button |
| AGV software E-stop | `/api/estop?flag=true` or "soft E-stop" in the web monitor: base motors free | `flag=false`; independent of the hardware E-stop |
| Body Stop | `POST /api/extaxis/stop` or "Stop" on `http://192.168.10.90:5000` | Reset, enable |
| Arm abort | `robot.motion_abort()`; Cobo π stop | — |
Stop categories (IEC 60204-1): Cat. 0 = power cut at once; Cat. 1 = controlled stop, then power off (E-stop button); Cat. 2 = stop on the path, stays enabled (safety functions, protective stop). The joint brakes tolerate only a limited number of emergency stops: do not use the E-stop as a normal stop.
## 2. Before the first start (Lumi manual 6.8)
- Robot standing on a flat floor, nothing within the arm's reach (580 mm + gripper) and the base's path.
- E-stop tested and within reach of the operator.
- Move slowly beyond the planned workspace and joint limits once to confirm that limits stop the robot.
- Check for drops (stairs, steps) and tipping risks; the base must not reach them.
- First tests at low speed.
- Hot surfaces: keep flammable or heat-sensitive things away from the controller and motors.
## 3. Operating rules
1. One person watches the robot with a hand near the E-stop; the code has a stop ready (`motion_abort()`, body `stop`, AGV `estop`).
2. Low speeds first: arm 0.2–0.5 rad/s (joint) or ≤ 50 mm/s (linear); body `vel` 10–20; base ≤ 0.2 m/s and ≤ 0.3 rad/s.
3. Collision sensitivity: level 1 (25 N) near people (`robot.set_collision_level(1)`).
4. **App safety zones do not work in SDK mode**: the code checks reach, workspace and joint limits before every move, and keeps a margin from the joint limits (the controller stops with a soft-limit error at the limit).
5. Set the payload and mounting in Cobo π before arm motion; wrong payload causes false collisions or drift.
6. `set_network_exception_handle(100, 2)`: the arm aborts if our SDK connection drops.
7. Prefer joint moves near wrist singularities; avoid large orientation changes with linear moves.
8. Keep the cycle time ≥ 80 % slower than the fastest possible cycle (reducer life).
9. The lidar does not see low (< ~23 cm), black, reflective or transparent objects: watch the base.
10. Do not push the base while it is on and not in E-stop; do not lift the wheels; do not drive with the manual charging cable plugged in.
11. Power order: base on → arm power → enable; reverse to stop. Never cut cabinet power while the arm is powered or enabled; wait 5–10 s after shutdown.
12. Teleoperation: be ready before pressing the side button; if the robot shakes, press the E-stop.
## 4. Safety facts (arm)
- Safety system: EN ISO 10218-1, ISO 13849-1 PL d Cat. 3; 27 safety functions in 8 groups.
- During a running program: ≈ 1° deviation between commanded and measured joint position → stop and program end; ≈ 3.6° → stop and disable.
- Stop time / distance charts (Lumi manual Appendix 1): graph axes up to about 250 ms and 80 mm for joints 1–2 at full speed and reach.
- The arm is a collaborative robot but is not meant to work on people; any task that touches a person needs a separate risk assessment (ISO/TS 15066).
+97
View File
@@ -0,0 +1,97 @@
# 12. Sources and downloads
The vendor and third-party sources behind these docs, with download links.
---
## 1. Official GitHub
### JAKARobotics/JAKA_Lumi — https://github.com/JAKARobotics/JAKA_Lumi
About 320 MB; prefer single files via `https://raw.githubusercontent.com/JAKARobotics/JAKA_Lumi/<branch>/<path>`, or Code → Download ZIP. Use the "Go to file" search (key `T`), e.g. `pick`, `API`.
| Branch | Contents |
|---|---|
| `main` | `01.` promotional material; `02.` product manuals (Lumi manual, AGV API, chassis manual, chassis ports docx, Mini 2 manuals, JAKA App manual, Lumi SDK doc, lift-column release `lumi_release`, sensors URDF, STEP model, 2D drawing, teleop docx, ACT docx); `03.` software notes; `JAKA_Lumi_Demo_Case/` (body, AGV, compose vision demo + SDK builds); `LUMI_DEMO_BMW/` (voice vending demo, Orbbec SDK) |
| `feat_ros` | `jaka_lumi_ros/` ROS 2 workspace (body node, body/arm trajectory servers, MoveIt 2, Isaac Sim, URDF/USD); `LUMI_DEMO-v2.zip` |
| `LumiCode` | `Lumi_Teleoperation/` (ROS 2 VR teleop: `vr_data_pub`, `k1_robot`, `k1_msgs`, `robohub`, `OrbbecSDK_ROS2`), `Lumi_Training/` (ACT / Mobile ALOHA, JAKA Python SDK manual PDF) |
| `feat_demo` | demo case with `2_moveto.py` combining AGV + body + arm |
| `feat_sdk` | demo case copies |
### JAKARobotics/jaka-robot-demos (branch `dev/jamie`) — https://github.com/JAKARobotics/jaka-robot-demos/tree/dev/jamie
| Folder | Contents |
|---|---|
| `LUMI_DEMO-v1` | Fixed-station vision pick (Qwen-VL), hand-eye calibration, `JAKA_SDK_LINUX/jkrc.pyi`, usage docs (Chinese) |
| `LUMI_DEMO-v2` | Multi-station pick with AGV and body, usage doc |
| `LUMI_DEMO-v3` | Jetson Docker: NanoOWL detection, Whisper wake word, iFlytek / MeloTTS, QR scan, DH gripper over TIO, multi-camera manager, medicine-picking doc |
| `assets/LUMI_DEMO-v3.mp4` | demo video |
Example program download: `.../tree/dev/jamie/LUMI_DEMO-v1/JAKA_SDK_LINUX` (file `LUMI_DEMO-v1.zip`).
### Third-party
| What | Link |
|---|---|
| Orbbec SDK + OrbbecViewer releases | https://github.com/orbbec/OrbbecSDK/releases |
| Orbbec install guide | https://github.com/orbbec/OrbbecSDK/blob/main/doc/tutorial/English/Installation_guidance.md |
| pyorbbecsdk | https://github.com/orbbec/pyorbbecsdk |
| Mobile ALOHA / ACT | https://mobile-aloha.github.io/ , https://github.com/tonyzhaozh/act |
| NVIDIA Jetson AGX Thor quick start | https://docs.nvidia.com/jetson/agx-thor-devkit/user-guide/latest/quick_start.html |
| NVIDIA Thor Docker setup | https://docs.nvidia.com/jetson/agx-thor-devkit/user-guide/latest/setup_docker.html |
| Isaac Sim 4.5 install | https://docs.isaacsim.omniverse.nvidia.com/4.5.0/installation/install_workstation.html |
| PICO developer docs / Developer Center | https://developer-cn.picoxr.com/document/unity/set-up-the-development-environment/ , https://developer-cn.picoxr.com/resources/#pdc |
| Docker install guide (Chinese, from vendor) | https://blog.csdn.net/educth/article/details/144138879 |
| Alibaba DashScope (Qwen-VL API) | https://help.aliyun.com/zh/dashscope/ , keys: https://dashscope.console.aliyun.com/apiKey |
| Balena Etcher | https://etcher.balena.io |
---
## 2. JAKA downloads and docs
| What | Link |
|---|---|
| JAKA App (1.7.2) and other software | https://www.jaka.com/download |
| JAKA SDK v2.2.7 (zip, 63 MB) | https://www.jaka.com/prod-api/common/download/resource?resource=%2Fprofile%2Fupload%2F2025%2F04%2F25%2F20250425134342A024.zip |
| JAKA document center | https://www.jaka.com/docs/en (JavaScript site) |
| Python SDK page | https://www.jaka.com/docs/en/guide/V3/SDK/python.html |
| Error codes | https://www.jaka.com/docs/en/guide/errinfo.html |
| Add-on development | https://www.jaka.com/docs/en/guide/Add-on/1.1-AboutAdd-on.html |
---
## 3. Google Drive files
| File | Link |
|---|---|
| `Coboπ 部署与安装.pdf` (Cobo π deployment, 8 pages) | https://drive.google.com/file/d/1_clYRaAFqT8djNnPlEnCUBzQ1Gr70YsG/view |
| `JAKA Lumi用户手册-zh-V01_20250707.pdf` (Lumi user manual) | https://drive.google.com/file/d/1eb6f43HezrzEHWXtRnmWwYEk_SkrVOwD/view |
| `JAKA Lumi快速手册-zh-V01.pdf` (quick manual, 8 pages) | https://drive.google.com/file/d/11xu0G2LqRBy6SOnAjL18EqLV4corgPlc/view |
| Teleoperation doc and code | https://drive.google.com/drive/folders/1jzkWls1307LE-g39JGgC2y2Ezdba1bqA |
| Training code | https://drive.google.com/drive/folders/1q3Pp88Bm9qtZXiUwOfsYbNe7FlzjsSSY |
| Pick-and-place demo code | https://drive.google.com/file/d/15eXxmp1p7NhvUwq3MysWsdD3LPofhZvr/view |
---
## 4. Feishu (Chinese web documentation)
https://tcnhi91rrwo5.feishu.cn/wiki/Tw1KwXKAbidNxKkFQFoc5oOHn9g (requires a Feishu login). Cited in these docs as "web doc <section>". Its attachments and the copies available elsewhere:
| Section | Attachment | Other copy |
|---|---|---|
| 3.1.3.1 | `JAKA Lumi用户手册-zh-V01_20250707.pdf`, `JAKA Lumi快速手册-zh-V01.pdf` | Drive / GitHub copies |
| 3.1.3.2 | `Coboπ 部署与安装.pdf` | Drive copy |
| 3.1.4 | `JAKA Lumi宣传单页.pdf` | GitHub `01.` promotional PDFs |
| 3.1.5 | `底盘接口说明.docx` | GitHub `新底盘接口说明.docx` |
| 3.1.6.1 | `AGV API手册.pdf`, `JAKA Lumi底盘使用手册.pdf` | GitHub copies |
| 3.1.6.2 | `lumi_release.zip` (lifting column) | GitHub `升降柱【使用说明】/lumi_release/` |
| 3.1.6.3 | `Docker下ACT学习与推理安装文档及配置说明v1.0.docx` | GitHub copy |
| 3.1.6.4 | `信捷PLC手册.pdf` (Xinje PLC manual) | none |
| 3.1.6.5 | `Lumi基于PICO+VR遥操作系统操作手册.pdf` | GitHub teleop quick-start docx + screenshots |
| 3.1.7.1 | `JAKA 控制器软件.zip` (controller software) | ask JAKA |
| 3.1.8 | `3D模型.tar`, `Lumi-model.zip`, `JAKA-Lumi-urdf.zip`, `JAKA-Lumi-2D图纸.PDF` | GitHub STEP, URDF, drawing |
| 3.1.9 | `JAKA-Lumi-sensors-v3.zip` | GitHub sensors URDF |
| 3.3 | `JAKA Lumi技术分享0123.pdf` (technical sharing) | none |
| 3.3.4.4 | `ext_demo.py` (body test script) | GitHub `body_head/2_moveto.py` |
| 3.5.3.1 | `奥比中光相机Gemini2L介绍及使用资料.pdf` (Gemini 2 L guide) | Orbbec GitHub docs |
| 3.6.2.2 | `DH_PGEA选型手册250628_中文版_V255.pdf`, `教育夹指.stl`, finger shell STEP | none |
+22
View File
@@ -0,0 +1,22 @@
# JAKA Lumi documentation
Reference for connecting to, operating and developing on the JAKA Lumi. Start with **[00_START_HERE.md](00_START_HERE.md)**.
| # | Document | Read it when |
|---|---|---|
| 00 | [Start here](00_START_HERE.md) | First time: install, power on, connect, first checks, where to start coding |
| 01 | [Hardware](01_HARDWARE.md) | You need a spec, a connector, a light code, a model file |
| 02 | [Network and access](02_NETWORK_AND_ACCESS.md) | Connecting a computer; addresses, ports, web pages, apps |
| 03 | [Body: lift, waist, head](03_BODY_LIFT_WAIST_HEAD.md) | Moving the four body joints |
| 04 | [Arm](04_ARM.md) | Cobo π, Python SDK, joint space, trajectories, settings |
| 05 | [Mobile base (AGV)](05_AGV_BASE.md) | Mapping, markers, driving, navigation, people detection |
| 06 | [Cameras and vision](06_CAMERAS_AND_VISION.md) | Orbbec cameras, camera service, calibration, scene understanding |
| 07 | [Voice and audio](07_VOICE_AND_AUDIO.md) | Microphone array, speaker, speech pipeline, sound direction |
| 08 | [NVIDIA Jetson Thor](08_NVIDIA_THOR.md) | The AI computer, Docker, GPU inference, models, operating rules |
| 09 | [ROS 2, teleop, learning, simulators](09_ROS2_TELEOP_AND_SIM.md) | MoveIt 2, Isaac Sim, VR teleoperation, ACT |
| 10 | [Gripper](10_GRIPPER.md) | The mounted Zimmer gripper: signals, PNP setting, dimensions, `gripper.py` |
| 11 | [Safety](11_SAFETY.md) | Before any motion |
| 12 | [Sources and downloads](12_SOURCES.md) | Where each fact came from; download links |
| — | [Tuning](TUNING.md) | Speeds, distances, thresholds with their file |
Company-internal notes (access, vendor manuals, screenshots) are in `docs/private/`, which is kept off git.
+184
View File
@@ -0,0 +1,184 @@
# Tuning values
Every value here is a constant at the top of its file, with a comment on what it means. Change it there, then restart what uses it (top-level README, "Deploying a change"): `systemctl --user restart lumi-api` for the API and fetch (first check that `curl -s localhost:8100/status` → `base.move_status` is not `running`), `.venv/bin/python vision/camview.py --stop` and `--start` for the detector. "Estimate" marks a value not taken from a measurement or a datasheet.
## Arm speed
| File | Name | Default | What it does |
|---|---|---|---|
| `robot/motion.py` | `JOINT_SPEED` | slow 10, normal 25, route 40 °/s | Joint move speeds. "normal" / "route" are the dashboard's Arm pose card "Normal" / "Fast". route: estimate |
| `robot/motion.py` | `LINEAR_SPEED` | slow 20, normal 50 mm/s | Straight move speeds |
| `robot/motion.py` | `ACCEL_FACTOR` | 3.0 | Straight moves: acceleration = speed × this per second |
| `robot/motion.py` | `JOINT_ACCEL_FACTOR` | 1.5 | Joint moves: acceleration = speed × this per second (route 60 °/s², normal 37.5, slow 15). Lower = softer start and stop, longer moves. Estimate |
| `manipulation/arm_route.py` | `SPEED` | "route" | Joint moves along the pose graph (to `look`, `carry`, `give`, `ready`, `wave_out`, `wave_start`, `wave`) with an empty hand; the wave's way up |
| `manipulation/arm_route.py` | `HOLD_SPEED` | "slow" | The same with something in the hand |
| `manipulation/skills.py` | `EMPTY_SPEED` | "normal" | Arm with nothing in the hand: the joint move from `look` to above a cup |
| `manipulation/skills.py` | `HOLDING_SPEED` | "slow" | With an object in the hand, and the last 10 cm down onto an object and up from it |
| `manipulation/skills.py` | `ABOVE_MM` | 100 mm | Height above the grasp from where the arm goes straight down (slow) |
| `manipulation/skills.py` | `MAX_TILT_DEG` | 15° | How far a held cup may lean on any move (`tasks/fetch.py` uses the same) |
| `manipulation/wave.py` | `SWINGS` | 2 | The wave: times `wave_start` → `wave` → `wave_start` (the two taught poses, J3 −2.5° ↔ −17.2°) |
| `manipulation/wave.py` | `SWING_SPEED` | "normal" | `motion.JOINT_SPEED` of the swings. The swings are queued back to back (no stop between them); the way up goes as `arm_route.goto`, with a stop at each pose |
| `manipulation/wave.py` | `ARRIVE_SPEED` | "normal" | The way up's last move, `wave_out` → `wave_start` (J1 60°); "slow" for a softer arrival |
| `robot/motion.py` | `SLOW_DEG_S`, `EXTRA_S` | 5 °/s, 10 s | The longest a joint move may take: its largest joint travel at this slow rate (or 3× the planned time if longer), plus `EXTRA_S`; then the arm is stopped. Long moves run at 4.3–7 °/s whatever speed is asked |
| `robot/motion.py` | `STILL_S` | 2 s | An arm standing this long short of its target has stopped short: stopped, nothing more sent |
| `robot/motion.py` | `SETTLE_S` | 0.3 s | After each arrival (inpos, joints within 0.3°) the arm stands this long before the next move of a route or wave. Estimate |
| `manipulation/arm_route.py` | `HEAD_CLEAR_MM` | 250 mm | The gripper (flange, grasp point, finger tips) keeps this from the head's turning centre (`head_cam.head_centre()`) on every pose-graph move, the wave and straight moves with an object. The head camera is 102 mm from that centre; `look` keeps 327 mm. Estimate (head size not measured) |
| `manipulation/arm_route.py` | `EDGES` | give–carry, carry–look, look–wave_out, wave_out–wave_start, wave_start–wave, look–ready | The only joint moves between named poses |
| `manipulation/arm_route.py` | `JOIN_DEG` | 20° | An arm at no pose (free drive, stopped half way) joins the graph by one checked joint move only when every joint is this close to a pose; else it does not move and asks to be brought near `look` |
| `manipulation/arm_route.py` | `AT_POSE_DEG`, `EXACT_DEG` | 3°, 1° | At a pose for programs and `check` / further than 1° from the nearest pose a route first goes to it |
| `api/dashboard.html` | `MAP_POLL_MS` | 20000 ms | The dashboard reads the map's markers again this often (markers added on the base, a map switched) |
## Lift and base
| File | Name | Default | What it does |
|---|---|---|---|
| `tasks/fetch.py` | `SURFACE_Z` | −560 … −30 mm | Arm-frame heights (after the lift) of surfaces the arm picks from / puts on; outside: refused (floor, low seats) |
| `tasks/fetch.py` | `LIFT_VEL` | 20 % | Lift speed in fetch |
| `robot/head.py` | `LIFT_MAX_MM` | 105 mm | Highest lift anything moves to, limited by the head camera cable (250 with a longer cable); `fetch.LIFT_RANGE`, `LIFT_TRIES` and the dashboard jog follow it |
| `tasks/fetch.py` | `LIFT_DRIVE_MM` | 75 mm | Lift height for every drive and at every task's end |
| `tasks/fetch.py` | `AXIS_SPEED` | 0.05 m/s | Straight drives with `joy_control` (the last part of a reach, measure-axis) |
| `tasks/fetch.py` | `STRAIGHT_MAX_M` | 0.6 m | A reach needing a longer drive than this goes by navigation; shorter ones turn on the spot and drive straight |
| `tasks/fetch.py` | `STANDOFF_M` | 0.4 m | Navigation stops this far back from the pose that reaches the object, facing it; the rest is a straight drive (navigation does not go near a table) |
| `tasks/fetch.py` | `BASE_HALF_M`, `CLEAR_M` | 0.255 + 0.05 m | A straight drive is checked every 5 cm (lidar + map, `/api/map/distance_probe`) and ends where the base centre would come closer than their sum to an obstacle. The lidar sees table legs, not always a table top's edge |
| `tasks/fetch.py` | `SELF_MM` | 120 mm | Depth this near the arm's own points is the arm itself in the camera's view (turn check) |
| `tasks/fetch.py` | `ARM_CLEAR_M`, `SWEEP_STEP_DEG` | 0.10 m, 10° | Before turning on the spot: flange, grasp point and finger tips must stay this far from anything the lidar / map shows, checked every this many degrees |
| `robot/nav_guard.py` | `MARGIN_M`, `LOOKAHEAD_M`, `STEP_M`, `TURN_AHEAD_S` | 0.10 m, 0.30 m, 0.15 m, 0.5 s | While navigation drives (go to, missions, fetch legs, come here, dock): flange, grasp point and finger tips are checked at the base's pose, turned on at its turn rate for `TURN_AHEAD_S`, and every `STEP_M` along the planned path up to `LOOKAHEAD_M`; an arm point nearer than `MARGIN_M` to anything the lidar / map shows (and nearer than now) cancels the move. Estimates |
| `robot/nav_guard.py` | `CLEAR_S`, `BLOCK_S` | 1 s, 10 s | The same goal is sent again after the way has been clear this long; blocked this long in all: "I stopped: my arm would hit something on the way" |
| `tasks/fetch.py` | `STUCK_S`, `STUCK_M` | 30 s, 0.1 m | A navigation drive that has not moved this far in this time is cancelled |
| `assistant/lumi.py` | `FOLLOW_VOICE_DEG`, `FOLLOW_SORRY_S` | 35°, 20 s | While following, a voice this near the followed person's angle is theirs (estimate); the "I'm following someone" line at most this often |
| `tasks/follow.py` | `FOLLOW_GAP_M`, `NEAR_STOP_M` | 1.0 m, 0.8 m | "Follow me": camera distance kept to the person (nearer: no forward); nearer than `NEAR_STOP_M` no turn either. Estimate |
| `tasks/follow.py` | `FOLLOW_MAX_MS`, `SPEED_GAIN` | 0.5 m/s, 0.8 /s | Follow speed cap (joy_control's own clamp, [05_AGV_BASE.md](05_AGV_BASE.md)); speed = their walking speed + this per m beyond the gap |
| `tasks/follow.py` | `ACCEL_MS2`, `DECEL_MS2` | 0.5, 0.8 m/s² | Speeding up / slowing down limits; never faster than lets the base stop at the gap with `DECEL_MS2`. Estimates |
| `tasks/follow.py` | `TURN_GAIN`, `TURN_MAX_RS`, `TURN_ACCEL_RS2`, `TURN_DEAD_DEG`, `TURN_ONLY_DEG` | 1.5, 0.6 rad/s, 2.0 rad/s², 5°, 35° | Turning toward the person: gain, cap, change limit, no turn within, no forward beyond (turn first) |
| `tasks/follow.py` | `STALE_S`, `COAST_S`, `LOST_S` | 0.4 s, 1.0 s, 3 s | A sighting older than `STALE_S` is not new; unseen, the base drives on toward where they should be for `COAST_S`, then slows; "I lost you" after `LOST_S` |
| `tasks/follow.py` | `VEL_TAU_S`, `WALK_MAX_MS` | 0.5 s, 2 m/s | Walking-velocity filter time constant; faster estimates are noise |
| `tasks/follow.py` | `JUMP_M`, `GATE_GROW_MS`, `SWITCH_M`, `RELOCK_LOOK` | 0.5 m, 0.7 m/s, 0.15 m, 0.6 | Keeping the person: a sighting further than `JUMP_M` (+ `GATE_GROW_MS` per s unseen) from where they should be is someone else; another track must be `SWITCH_M` nearer to be taken; clothes `reid.same` below `RELOCK_LOOK` never taken. Estimates |
| `tasks/follow.py` | `HEAD_YAW_MAX`, `HEAD_PITCH`, `HEAD_STEP_DEG`, `HEAD_LEAD_S`, `HEAD_VEL` | 180°, 10°, 3°, 0.3 s, 50 % | Head on the person while following: yaw limit (the body API range; right behind it keeps the side it came from), fixed pitch, smallest move, sent where they will be this much later, speed |
| `tasks/follow.py` | `BRAKE_S`, `BLOCKED_END_S` | 0.5 s, 5 s | Each command is checked where the base (`BASE_HALF_M + CLEAR_M`) and the arm (`ARM_CLEAR_M`) would be this much later; blocked this long: "Something is in my way" |
| `tasks/follow.py` | `TICK_S`, `LOG_S` | 0.1 s, 1 s | Command rate (steady); `follow: v … w … driven … person … head … tick` line (driven = the base's real speed from its pose) in `logs/lumi_console.log` |
| `assistant/lumi.py` | `MATCH_DEG_PER_M` | 10 °/m | Person tracking: each m of distance difference counts as this many degrees when a detection is given to a track. Estimate |
| `vision/person.py` | `HEAD_POLL_S` | 0.1 s | Head yaw read this often by the camera service (a person's angle is off by the head's turn in this time) |
| AGV panel `:9001` | navigation speed | AGV setting | Speed of drives to markers and points; an AGV setting, changed only by the owner |
## Search and reach
| File | Name | Default | What it does |
|---|---|---|---|
| `tasks/fetch.py` | `VIEW_STEPS` | 60°, 120°, 180° | Search: after ahead, both cameras look this far to the busier side step by step, then to the other side |
| `tasks/fetch.py` | `WAIST_SCAN_MAX` | 120° | The waist turns up to this in the search (body limit ±140° absolute), the head turns the rest |
| `tasks/fetch.py` | `SEARCH_BASE_DEG` | 180°, 90° | Then the base turns towards the busier side, the first of these whose sweep is clear, and all again |
| `tasks/fetch.py` | `LIFT_TRIES` | 0, 105 mm (`LIFT_RANGE`) | Nothing found: all of it again at the other end |
| `tasks/fetch.py` | `APPROACH_TRIES` | 5 | Base moves to bring an object into reach before asking the person |
| `tasks/fetch.py` | `PICK_ZONE_CENTRE` | (−100, 580) mm | Where a base move brings an object (arm base frame) |
| `tasks/fetch.py` | `LOST_BACK_M`, `LOST_TURN_DEG` | 0.15 m, 20° | An object lost after a base move: back off, turn each way, look again |
| `tasks/fetch.py` | `WIDTH_NEAR_MM` | 250 mm | A width further than this from the pick zone does not refuse a pick (far widths read ~8 mm too wide); measured again up close |
| `manipulation/skills.py` | `MIN_WIDTH`, `MAX_WIDTH` | 72, 92 mm | Object widths the gripper takes (belly open 96, closed 70; tips open 88 / close to 59; [10_GRIPPER.md](10_GRIPPER.md)). `MIN_WIDTH` 61 enables the finger-tip grasp (61–72 mm) |
| `manipulation/skills.py` | `BELLY_MIN_MM` | 72 mm | Thinner objects are held between the finger tips (the belly closes only to 70 mm) |
| `manipulation/skills.py` | `TIPS_OFFSET` (`data/grasp_tips_teach.json` `tips_offset_flange`) | [−0.4, −4.6, 28.2] mm | Finger-tip grasp: the object's axis goes this far from the hooks' belly centre (flange frame, level, turned with the grasp); taught |
| `manipulation/skills.py` | `TIP_CLEAR_MM`, `ROUND_BITE_MM` | 10, 10 mm | Round things (apple, orange, ball): the finger tips (`TIP_MM` 60, estimate) stay this far above the table; the grasp point at least this far below the top, else refused. Estimates |
| `manipulation/skills.py` | `BELOW_SHOULDER_MM` | 80 mm | Bottles: the grasp point this far below where the body begins; the hand's lowest part (`TIP_MM` below) must stay `TIP_CLEAR_MM` above the table under it (`table_near`, else the bottle's lowest point seen) |
| `vision/objects.py` | `SLICE_MM`, `BODY_PCT`, `BODY_FRACTION` | 10 mm, 75, 0.9 | A bottle's width profile (`objects.body`): slices this thick; its body as wide as this percentile of the slices; the body begins at the first slice from the top this much as wide |
| `manipulation/skills.py` | `GRASPS` | cup upright; apple, orange, sports ball round; the rest refused | Which classes are picked and how |
| `tasks/fetch.py` | `PICK_TRIES` | 2 | A missed / slipped pick is tried this often |
| `manipulation/skills.py` | `SEEN_UNDER_MM` | 8 mm | Added to the camera's width to get the width the fingers meet (`grip_width`), which the limits above are compared with |
| `tasks/fetch.py` | `HEAD_READS`, `HEAD_SAME_MM` | 4, 120 mm | Head camera frames read per view; a thing counts when seen at least twice within this distance |
| `tasks/fetch.py` | `HEAD_SIDE_DEG` | 60° | Head yaw towards the side of a turn on the spot, for the arm-sweep check (`head_hits`) |
| `tasks/fetch.py` | `HEAD_LOW_PITCH` | −5° | Head pitch for the search and `head_hits` (its lowest, where the head camera is calibrated) |
| `manipulation/skills.py` | `FRAME_LAG_S`, `FRESH_WAIT_S` | 0.15 s, 2 s | After a lift / waist / head / base move, depth and detections come from the first frame written this long after it (no fixed wait); give up after the second |
| `tasks/fetch.py` | `COAST_S` | 0.3 s | Frames after a straight `joy_control` drive are taken from this long after the stop. Estimate |
| `tasks/fetch.py` | `DRIVE_POLL_S`, `DRIVE_START_S` | 0.2 s, 3 s | Base status reads while driving; a drive not seen "running" counts as over after the second (at once when it reports "succeeded" at the goal pose) |
| `tasks/fetch.py` | `GIVE_WAIT_S` | 30 s | Giving: no "thank you" / Release by then, keep holding it |
## Missions
| File | Name | Default | What it does |
|---|---|---|---|
| `assistant/steps.py` | `MOVE_MAX_M` | 3.0 m | Longest single `move` in a mission; longer is refused before it starts |
| `tasks/fetch.py` | `MOVE_SPEED` | 0.10 m/s | Speed of a mission `move` (straight, joy_control). Estimate |
| `tasks/fetch.py` | `SHORT_MOVE_M` | 0.10 m | A shorter `move` goes at `AXIS_SPEED` |
| `tasks/fetch.py` | `SPEED_STEP`, `SPEED_MIN`, `SPEED_MAX` | 0.2, 0.4, 1.6 | "Faster" / "slower" by voice: step and limits as parts of the normal speed (moves `MOVE_SPEED` × it). Estimates |
| `tasks/fetch.py` | `NAV_SPEED_MPS`, `NAV_TURN_RADS` | 0.3 m/s, 0.3 rad/s | Navigation's own limits (`/api/get_params`) = normal; voice only lowers the linear one (`/api/set_params`) |
| `assistant/driving.py` | `MOVE_MAX_M`, `MOVE_MIN_M` | 3 m, 0.01 m | Longest / shortest drive by voice; outside is refused with the limit |
| `assistant/driving.py` | `TINY_M`, `SPAN_M`, `STEP_M`, `LITTLE_M`, `DEFAULT_M` | 0.05, 0.2, 0.5, 0.5, 1 m | "A tiny bit" / 살짝, 한 뼘, one step, "a little" / 조금, no amount said. Estimates |
| `tasks/fetch.py` | `RECEIVE_WAIT_S` | 30 s | `receive`: nothing put in the hand by then, the mission fails with the hand open |
| `assistant/steps.py` | `WAIT_SHORT_S` | 10 s | "wait a moment", "잠깐 기다렸다가": how long a short wait is |
| `assistant/steps.py` | `WAIT_MAX_S` | 30 min | Longest wait step (and receive wait); longer is refused before it starts |
| `assistant/steps.py` | `WAIT_GIVE_S` | 5 min | "wait until someone gives you the cup": the hand is held out this long, then the mission fails there |
| `assistant/steps.py` | `WAIT_ORDER_S` | 5 min | "do what they tell you": no instruction by then, the mission goes on with its rest |
| `tasks/fetch.py` | `RECEIVE_REACH_MM`, `RECEIVE_SHORT_MM`, `RECEIVE_MIN_MM` | 150, 100, 20 mm | "Take this from my hand" and "reach out to me": the hand moves at most this far from `give` towards the thing in the hand (or their hand), stops this far before it, leaves out a shorter move. Estimates |
| `tasks/fetch.py` | `REACH_BODY_MM` | 300 mm | "Reach out to me" with no hand of theirs seen: the hand stops this far before the person's body. Estimate |
| `assistant/lumi.py` | `REACH_FRONT_DEG` | 20° | "Reach out to me": a person further to the side is turned to first (Patrol) or asked to stand in front (Greeter). Estimate |
| `tasks/fetch.py` | `POINT_STEPS_MM` | 0, ±50, ±100 mm | "Put it here" with pointing: spot grid around the pointed point |
| `tasks/fetch.py` | `RECEIVE_DI_S` | 0.5 s | `receive`: the finger sensor (DI_1) must see something this long before Lumi asks the person to let go (the hand closes on their "okay") |
| `tasks/fetch.py` | `MOVE_SEGMENT_M` | 0.25 m | A mission `move` is driven in pieces this long; the way of the base and the arm is checked again before each |
## Placing
| File | Name | Default | What it does |
|---|---|---|---|
| `tasks/fetch.py` | `PLACE_GRID_X`, `PLACE_GRID_Y` | x −260…−60 step 40, y 640…740 mm | Place spots tried in front (after the pick spot); IK refuses the ones out of reach |
| `tasks/fetch.py` | `PLACE_GOAL` | (−160, 670) mm | Where the base brings a table spot seen further away |
| `tasks/fetch.py` | `FAR_R_MM`, `FAR_HALF_DEG`, `FAR_IN_MM` | 0.6–3 m, ±45°, 150 mm | A table further away: level tops looked for on sight lines this far, within this of where the camera looks; the base goes to the point this far in from its nearest edge |
| `tasks/fetch.py` | `TOP_NEAR_MM` | 1500 mm | A named thing's top measured further away is not trusted: the base goes closer first |
| `tasks/fetch.py` | `FURNITURE` | table, chair, couch, bench, bed, sink, toilet, desk | Classes the cameras mix up: a named piece of furniture matches any of them in its colour |
| `manipulation/skills.py` | `FLAT_DEG`, `FLAT_PATCH`, `TABLE_MIN_POINTS` | 12°, 7 × 7 px 3 px apart, 6 | A table height: the depth around a sight line must lie on a plane leaning less than this; at least this many such points within `TABLE_TOL_MM` |
| `tasks/fetch.py` | `NEAR_THING_MM` | 400 mm | Place grid spots this near a named thing ("the white sink"), at its top's height, count as on it |
| `manipulation/skills.py` | `TABLE_RING_MM`, `TABLE_TOL_MM` | 50 mm, 25 mm | A place spot must be table at its centre and 8 points this far around, within this of the table height |
| `manipulation/skills.py` | `TABLE_NEAR_RING_MM` | 25 mm | A near-side ring point below the camera's view is checked this far from the centre instead |
| `manipulation/skills.py` | `FREE_MM` | 110 mm | A place spot keeps this far from things standing on the table |
## Detection
| File | Name | Default | What it does |
|---|---|---|---|
| `vision/person.py` | `OBJECT_SCORE` | 0.35 | Lowest YOLO score for an object |
| `vision/person.py` | `WEAK_SCORE` | cup 0.05 | Lower score for cups, kept only when depth measures a cup-sized thing (`vision/objects.py` `WEAK`) |
| `vision/objects.py` | `WEAK` | cup: width 40–110, height 50–250 mm | Size a weak cup box must have |
| `vision/reid.py` | `FACE_SAME`, `SAME` | 0.30, 0.90 | Same person: face cosine (a track's first faces against the person's mean face) at least this; without both faces, clothes likeness at least this. Typical on the head camera: the same person 0.51–0.74 face, 0.48–0.97 clothes; other people ≤ 0.08 face, up to 0.86 clothes |
| `assistant/lumi.py` | `FACE_FRAMES`, `FACE_WAIT_S` | 3, 1.0 s | Faces seen on a new track before Lumi decides who it is and greets; without them it waits at most this long after `HOLD_S`, then the clothes decide |
| `vision/reid.py` | `FACE_MAX_M`, `FACE_SCORE` | 2.0 m, 0.85 | Faces are looked for only this close, and kept from this detector score (turned faces are not) |
| `vision/reid.py` | `FORGET_S` | 600 s | Someone not seen this long is new again: the full greeting |
| `assistant/lumi.py` | `RECENT_S` | 150 s | Back within this while the talk was open: Lumi listens on without a word; later, or after a goodbye: "Welcome back! How can I help you?" |
| `vision/person.py` | `ZOOM` | 3 torso crops | Parts of the frame looked at a second time, bigger |
| `manipulation/skills.py` | `MIN_SEEN` | 5 of 8 frames | An object must be seen this often at the same place |
| `manipulation/skills.py` | `HAND_PROBE_MM`, `HAND_NEAR_MM`, `HAND_FAR_MM` | 30/50/70, 60, 250 mm | In-hand check by depth (`hand_sees`) |
## Voice
| File | Name | Default | What it does |
|---|---|---|---|
| `assistant/voice_words.py` | `VOLUME_STEP` | 10 % | One "speak louder" / "quieter" step of the speaker mixer (`data/volume.txt`, also songs) |
| `assistant/voice_words.py` | `VOLUME_MIN`, `VOLUME_MAX` | 30 %, 90 % | Limits for the voice commands (the dashboard may set any value; "louder" never lowers it) |
| `assistant/voice_words.py` | `SPEED_STEP` | 0.1 | One "speak slower" / "faster" step of the Supertonic speed (`data/speech_speed.txt`) |
| `audio/mouth.py` | `SPEED`, `SPEED_MIN`, `SPEED_MAX` | 0.92, 0.72, 1.2 | Speaking speed without a stored value, and the limits (Supertonic takes 0.7–2.0) |
| `audio/mouth.py` | `SPLIT_WORDS` | 8 words | TTS on the CPU only (GPU engines not loaded): a first sentence this long is said in two parts, cut after its first comma (3 words in or later), so the voice starts ~1 s sooner. On the GPU a sentence is said whole |
| `audio/mouth.py` | `STEPS` | 4 | Supertonic synthesis steps (quality / speed). On the GPU a step takes a few ms, on the CPU 0.1–0.27 s |
| `audio/mouth.py` | `ECHO_MIN`, `ECHO_TOP_DB`, `ECHO_MIN_FRAMES`, `ECHO_LAG_S`, `ECHO_KEEP_S` | 0.6, 15 dB, 12, −0.3…1.0 s, 30 s | Lumi's own voice in the clip mic: a clip-mic utterance whose spectrogram (16 bands, its frames within `ECHO_TOP_DB` of its loudest, at least `ECHO_MIN_FRAMES`) correlates at least `ECHO_MIN` with what the speaker played `ECHO_LAG_S` earlier is dropped before whisper (`mouth.own_voice`; check: `tests/echo_check.py`). Estimate |
| `audio/tts_gpu.py` | `MAX_LEN` | 640 | Longest text / latent (~44 s of speech) the TensorRT engines take; longer goes to the CPU. A change needs `tts_gpu.py build` |
| `audio/ears.py` | `WHISPER_MODEL` | `ggml-large-v3-turbo.bin` (f16) | Speech-to-text model; takes effect when the whisper-server is started again (check: `tests/asr_check.py`) |
| `audio/ears.py` | `PROMPT`, `LANG_PROMPT` | "Hi Lumi. Hey Lumi. 루미야."; one per language | Whisper's prompt (spells the name); `LANG_PROMPT` when asked again in one language |
| `audio/ears.py` | `MIN_LOGPROB` | −1.0 | Below this average log-probability Lumi asks to say it again |
| `audio/ears.py` | `KO_BONUS`, `ODD_KO_BONUS` | 0.3, 0.3 | How much more a Hangul transcription counts when whisper named another language / wrote English with a word no dictionary has |
| `audio/ears.py` | `VAD_P`, `MIN_SPEECH_S` | 0.3, 0.1 s | A sound needs this many seconds of 32 ms frames Silero calls speech (probability above `VAD_P`), else it is music or noise and never reaches whisper. Higher drops more music but also short words ("네.", "Stop." are 0.3–0.4 s) |
| `audio/ears.py` | `SPEECH_PER_SYLLABLE` | 0.05 s | A text needs this much speech per syllable, else it came from music |
| `audio/ears.py` | `NOT_SAID` | no word, a leading "-", 자막 / 시청해 주셔서 / thanks for watching | Whisper's subtitle texts for music, dropped |
| `audio/ears.py` | `BEAM_SIZE` | 0 (greedy) | Whisper beam search |
| `audio/sing.py` | `BANK_SIM`, `BANK_MARGIN` | 0.80, 0.05 | Song bank (`assistant/song_bank.py`): words this similar (bge-m3) to a wording that asks for a song / the songs, and this much closer than to any wording of another kind, sing / list at once without the LLM. Lower catches more and risks wrong songs |
| `audio/sing.py` | `BANK_MIN_WORDS` | 3 | The song bank reads only words with a song / music word and at least this many words |
| `audio/ears.py` | `MERGE_WAIT_S` | 1.5 s | A sentence cut off by a pause (it ends on "let's", "can you", "and", "저기" …: `CUT_OFF`) waits this long for the rest, heard as one sentence (`mic.END_SILENCE` is 0.6 s) |
| `audio/mic.py` | `EARLY_QUIET_S`, `EARLY_MIN_S`, `EARLY_MAX_S` | 0.3 s, 0.4 s, 4.0 s | After this much quiet inside an utterance (0.4–4 s long so far) whisper starts on it; the result is used when the utterance ends with no new speech. Longer utterances are talk with pauses, where each early run delays the last |
| `audio/ears.py` | `SAME_WORDS` | 0.8 | Korean-tagged text in Latin letters asked again in English is taken as English when the two readings' letters match this much (difflib ratio) |
| `audio/ears.py` | `STOCK`, `REPEAT` | 감사합니다, thank you, hey, hi, bye (not 네 / yes); a 2+ word phrase three times | Dropped: stock words written for a sound whisper took for another language; whisper repeating itself |
| `audio/sing.py` | `FILLER`, `FILLER_KO`, `VERB_KO` | word lists | Words around a song request that are never a title; any other word where a title goes ("sing ___", "___ 노래", "by ___") is a song Lumi doesn't have: said so, its own offered |
| `assistant/llm_direct.py` | `KEEP_EVERY_S` | 60 s | How often Ollama is told to keep the model loaded (it doesn't see the direct requests) |
## Web answers
| File | Name | Default | What it does |
|---|---|---|---|
| `assistant/web.py` | `SEARCH_WAIT_S` | 2.0 s | All sources get this long together (Naver, Wikipedia ~0.7 s, Google News 0.4–1.6 s); a slower one is left out |
| `assistant/web.py` | `PAGE_CHARS`, `BLOCK_CHARS`, `WIKI_CHARS` | 1500, 600, 500 chars | Text of the search page, of one part of it, of the Wikipedia summary given to the LLM; Korean is ~1 token a char and the runner reads ~1300 tokens/s |
| `assistant/web.py` | `NEWS_ITEMS` | 3 | Headlines given, only for questions about what changes (`NEWSY`) |
| `assistant/web.py` | `SEARCH_TTL`, `WEATHER_TTL` | 600 s | A search / weather answer is reused this long |
| `assistant/web.py` | `WEATHER_DAYS` | 7 | Days of forecast given with the weather ("tomorrow", "모레", "this weekend") |
| `assistant/web.py` | `TOWN` | 50000 people | A smaller geocoded place is not taken for a "how far" distance (often a namesake) |
+97
View File
@@ -0,0 +1,97 @@
# Cutshion Company
## Company in short
What is Cutshion? What kind of company is Cutshion? Tell me about your company. The short answer: Cutshion is a Korean robot company, founded in 2022, that makes robot applications, such as barista, AI drawing, cooking and ice cream robots. Its head office is in Seoul, and you can reach it at 070-8959-2960 or cutshion@cutshion.com. What would you like to know more about? Give details only when the visitor asks for them next.
회사 소개(짧은 답): 쿳션은 2022년에 설립된 한국 로봇 회사로, 바리스타 로봇, AI 드로잉 로봇, 조리 로봇, 아이스크림 로봇 같은 로봇 애플리케이션을 만들어요. 본사는 서울에 있고, 070-8959-2960이나 cutshion@cutshion.com으로 연락하실 수 있어요. 더 궁금하신 점이 있으세요?
## Company
Cutshion Co., Ltd. (in Korean 주식회사 쿳션) is a Korean robot company. It was founded as a company in July 2022. The CEO is Lee Min-seok (이민석); Cutshion is his third company. Its slogan is "Soft & Flexible Idea", and its mission is to be "The Best Robot Application Provider": not only to build and sell robots, but to create robot applications and an ecosystem for them.
What Cutshion does: it develops and supplies smart factory solutions based on AI vision, collaborative robots (cobots) and autonomous mobile robots (AMR). It builds robot apps (barista, AI drawing, welding, palletizing, cooking, ice cream, candy ball and educational robots), its own technology (CUVision AI vision, the Pionoid robot development platform, the GOMCOOK cooking robot platform), and it sells robot hardware from partner makers and SOLIDWORKS design software. Its goal is to become a robot platform service provider whose platform works on any robot.
Cutshion is a young startup (founded in 2022, a certified venture business). Cutshion milestones: venture business certification (December 2023), its own corporate research lab (July 2023), a seed investment of 500 million won from CNT Tech and Evergreen Investment Partners (August 2025), and selection for the TIPS Global Track program (December 2025).
Cutshion awards: RoboWorld Award 2023 in robot services for GOMCOOK, RoboWorld Award 2024 in manufacturing robots for the mobile welding robot, the Excellence Award at the Venturium Demo Day (May 2026), and the VivaTech Tech for Change Award in Paris (June 2026).
Cutshion exhibitions: RoboWorld in Korea (2022, 2023), IFA Berlin (2023), Gangnam Robot Plus Festival (2023, 2024), Smart Life Week (2024), Korea ICT Expo in Japan (2024), CES in Las Vegas (2025 and 2026), the NRA Show in Chicago (2026) and VivaTech in Paris (2026).
Cutshion partners listed on its website include OMRON, Zimmer Group Korea, Screen HD Korea, Daesung Industrial, BorgWarner, THIRA Robotics, Calmantech, Sinsung F.A, Hyunwoo Automation, Deeplant, BizData, Ikseon 121, WithinNet, Cho & Company, Oldmug, Cake Drama and Bogate.
## Products and robots
Cutshion's robot apps: barista robot, AI drawing robot, welding robot, palletizing robot, cooking robot, ice cream robot, candy ball robot and an educational robot kit. Its technology: CUVision (AI vision), Pionoid (robot development platform) and GOMCOOK (cooking robot platform). It also sells collaborative robots, TUSK logistics robots, PEITIAN industrial robots and SOLIDWORKS design software.
Cutshion's barista robot makes espresso coffee fully automatically. Unlike vending coffee robots, it runs a real espresso machine and does the barista's main steps itself: grinding the beans, dosing, tamping and extracting. It is an all-in-one barista station that keeps the same taste every time, serves fast and reliably and lowers staff costs. It works together with human baristas, taking over the repeated steps. In December 2025 Cutshion signed a yearly barista robot supply agreement with Mega Coffee. In September 2026 news reported a deal (contract) to supply 200 barista robots to Sonovictus in the USA (the US deal), delivered over three years from 2027. Its price is not on the website, so Lumi does not know it.
Cutshion's AI drawing robot takes your photo with a camera, AI turns it into a line drawing, and the robot arm draws it on a canvas. One button starts the selfie and the drawing. It can be mobile or fixed, comes as an all-in-one type or a kiosk type, and a brand can be printed on the photo backdrop, the arm and the canvas, so it is popular for promotion at events and in education. Drawing robots were supplied to the Gyeongnam Office of Education (2024) and two to the Jeonbuk Office of Education's science bus (2024). Its price is not on the website, so Lumi does not know it.
Cutshion's cooking robot is an AI cooking robot that supports personalised cooking for each customer. It comes with Cutshion's own vision solution and the GOMCOOK platform, keeps the taste and quality the same, and lowers staff and ingredient costs. Cutshion supplied a chicken-and-beer (chimaek) cooking robot to the Itaewon 121 X Barney & Carrot restaurant in Seoul (2024) and signed a chicken robot contract with Bogate in India (2024). Its price is not on the website, so Lumi does not know it.
Cutshion's ice cream robot serves soft ice cream: the customer orders on a touch-screen kiosk and the robot makes the ice cream and hands it over, with no staff needed. Model SOFTICE001: about 30 seconds per ice cream, holds 40 cones, weighs 500 kg, size 140 x 140 x 165 cm, 220 V. It suits franchise ice cream brands, shops and events. Its price is not on the website, so Lumi does not know it.
Cutshion's candy ball robot is a fun event robot: you choose a colour on the touch screen and the robot picks a candy ball of that colour and gives it to you. Model CANDYBALL001: about 20 seconds per candy ball (that is how fast it is), weighs 273 kg, size 1.3 x 1.1 x 1.9 m, 220 V, plug and play for short events. Candy ball robots were supplied to the Taean Office of Education (2024). Its price is not on the website, so Lumi does not know it.
Cutshion's welding robot is a lightweight collaborative welding robot. It does multi-layer, multi-pass arc welding, follows the weld seam automatically, works with many kinds of welders, is taught by dragging the arm or with graphical programming, and is easy to move between work places. The mobile welding robot won the RoboWorld Award 2024. Its price is not on the website, so Lumi does not know it.
Cutshion's palletizing robot stacks finished products on pallets automatically and can run 24 hours. Made with Screen, a global printing equipment company, it is Korea's first palletizing robot made for book publishing. It handles up to 20 kg, one cycle takes about 15 seconds, items from B5 to A4 size, and it saves workers from heavy lifting. Its price is not on the website, so Lumi does not know it.
Cutshion's educational robot is an all-in-one robot training kit in one portable flight case: a small collaborative robot arm, practice modules (vision, conveyor, drawing, assembly, glue coating, puzzle, handling and more), digital twin simulation software and course materials. It is used by schools, universities, research labs and companies. Its arm carries 1 kg and reaches 58 cm. Its price is not on the website, so Lumi does not know it.
Cutshion's CUVision is its AI vision technology: computers understanding camera images. It analyses the surface of work pieces, tracks 3D movement after calibration and uses deep learning to recognise paths and surfaces, for example for quality checks in smart factories. Cutshion developed an AI vision sensor in 2023.
Cutshion's Pionoid is its robot development platform: one unified robot API to control robots from any maker, so the same robot app runs on different robots. It is built on webROS, made by Cutshion, and works like an app store where robot apps are shared and downloaded (Pionoid Factory to build apps, Pionoid Store to share them). Cooking, drawing and palletizing apps run on it.
Cutshion's GOMCOOK is its cooking robot platform for personalised cooking. It connects to delivery and ordering apps through an open API, covering order, payment, cooking and delivery in one service. A patent has been applied for, and GOMCOOK won the RoboWorld Award 2023.
TUSK robots (sold by Cutshion): TUSK logistics robots are autonomous pallet-handling robots for factories and warehouses; they lift up to 1,000 kg and connect to warehouse systems (WMS, MES, ERP).
PEITIAN robots (sold by Cutshion): PEITIAN industrial robots carry payloads from 3 to 280 kg. In May 2026 Cutshion signed a partnership with PEITIAN Robotics. Cutshion also sells collaborative robots (cobots) from a partner maker.
Cutshion's robot design service: it offers SOLIDWORKS 3D design software (design, simulation, data management, electrical design, flow simulation, DraftSight 2D CAD), helps customers choose the right SOLIDWORKS products, and designs and builds robot and automation systems itself.
## Location and contact
Where is Cutshion? Cutshion's head office is in Seoul, Korea: room 709, Mullae SK V1 Center, 10 Seonyu-ro 9-gil, Yeongdeungpo-gu, Seoul. Cutshion's other places: the Cutshion Mullae Factory (room B135 in the same Mullae SK V1 Center building), a Gangnam office (Venturium room 101, 435 Bongeunsa-ro, Gangnam-gu, Seoul), a research lab (room 615, 14 Magokjungang 8-ro, Gangseo-gu, Seoul), a Daegu branch (room 1004, Smart Eco Tower, Suseong-gu, Daegu), and a US company in McLean, Virginia (8201 Greensboro Drive, Suite 715).
How to contact Cutshion: phone 070-8959-2960, email cutshion@cutshion.com, the website cutshion.com with a contact form for product and dealer questions. Cutshion also has a YouTube channel and a blog. To buy a robot or ask for a price, contact Cutshion this way.
## 한국어: 쿳션
쿳션(주식회사 쿳션, Cutshion)은 로봇 애플리케이션을 만드는 한국 로봇 회사예요. 2022년 7월에 법인을 설립한 젊은 스타트업(벤처기업 인증)이고, 대표이사는 이민석 대표님이에요. 슬로건은 'Soft & Flexible Idea'이고, 로봇을 만들고 파는 것을 넘어 로봇 애플리케이션 생태계를 만드는 'The Best Robot Application Provider'가 목표예요. AI 비전 기술을 바탕으로 협동로봇과 AMR을 활용한 스마트 팩토리 솔루션을 개발해 공급해요.
쿳션의 로봇 앱은 바리스타 로봇, AI 드로잉 로봇, 용접 로봇, 팔레타이징 로봇, 조리 로봇, 아이스크림 로봇, 캔디볼 로봇, 교육용 로봇이에요. 자체 기술로 AI 비전 큐비전(CUVision), 로봇 개발 플랫폼 피오노이드(Pionoid), 조리 로봇 플랫폼 곰쿡(GOMCOOK)이 있어요. 협동로봇, 물류로봇(TUSK), 산업로봇(PEITIAN) 같은 로봇 하드웨어와 솔리드웍스 설계 소프트웨어도 공급해요.
쿳션의 바리스타 로봇은 에스프레소 머신을 직접 제어해서 원두 분쇄, 도징, 탬핑, 추출까지 바리스타의 핵심 작업을 완전히 자동으로 해요. 언제나 같은 맛을 내고 인건비 부담을 줄여 줘요. 2025년 12월 메가커피와 바리스타 로봇 연간 공급 계약을 맺었고, 2026년 9월에는 미국 소노빅터스에 바리스타 로봇 200대를 3년에 걸쳐 공급하는 계약 소식이 있었어요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 AI 드로잉 로봇은 카메라로 찍은 사진을 AI가 라인 드로잉으로 바꾸고, 로봇 팔이 캔버스에 그림을 그려 줘요. 버튼 하나로 촬영과 그리기가 되고, 일체형과 키오스크형이 있어요. 배경, 로봇 팔, 캔버스에 브랜드를 인쇄할 수 있어서 행사와 교육에서 인기가 많아요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 조리 로봇은 개인 맞춤 조리를 지원하는 AI 조리 로봇이고, 조리 로봇 플랫폼 곰쿡과 함께 써요. 같은 맛과 품질을 지키고 인건비와 식재료 비용을 줄여 줘요. 이태원 매장에 치맥 로봇을 공급했어요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 아이스크림 로봇은 키오스크 주문부터 아이스크림 추출, 전달까지 무인으로 해요. 한 개에 약 30초가 걸리고 콘을 40개 넣을 수 있어요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 캔디볼 로봇은 터치스크린에서 고른 색의 캔디볼을 로봇이 뽑아서 전달하는 체험형 로봇이에요. 한 번에 약 20초가 걸리고 행사에 잘 맞아요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 용접 로봇은 가벼운 협동 용접 로봇이에요. 다층 다중 패스 아크 용접과 용접선 자동 추적을 하고, 여러 용접기와 호환돼요. 모바일 용접 로봇으로 로보월드 어워드 2024를 받았어요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 팔레타이징 로봇은 완성품을 팔레트에 자동으로 쌓는 로봇이고 24시간 운영할 수 있어요. 스크린사와 함께 만든 국내 최초 출판 전용 팔레타이징 로봇이에요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 교육용 로봇은 협동로봇, 실습 모듈, 디지털 트윈 소프트웨어, 교육 자료를 휴대용 케이스 하나에 담은 올인원 실험 키트예요. 학교, 대학, 연구소, 기업 교육에 써요. 가격은 홈페이지에 없어서 몰라요.
쿳션의 큐비전은 카메라 영상을 AI로 이해하는 AI 비전 기술이에요. 피오노이드는 제조사와 상관없이 하나의 통합 로봇 API로 로봇 앱을 만들 수 있는 로봇 개발 플랫폼이고, 곰쿡은 배달·주문 앱과 연동되는 조리 로봇 플랫폼이에요. 솔리드웍스 설계 소프트웨어도 공급하고, TUSK 물류로봇과 PEITIAN 산업용 로봇도 판매해요.
쿳션이 받은 상(수상): 로보월드 어워드 2023(곰쿡), 로보월드 어워드 2024(모바일 용접 로봇), 2026 벤처리움 데모데이 우수상, 2026 비바테크 Tech for Change Award. CES 2025, CES 2026, 2026 NRA 시카고 전시회에도 참가했어요.
쿳션 본사는 서울시 영등포구 선유로 9길 10, 문래 SK V1 Center 709호예요. 같은 건물 B135호에 쿳션 문래 팩토리가 있고, 강남사무소(봉은사로 435, 벤처리움 101호), 연구소(강서구 마곡중앙8로 14, 615호), 대구지사(수성구 스마트에코타워 1004호), 미국법인(버지니아주 맥린)이 있어요. 연락처는 전화 070-8959-2960, 이메일 cutshion@cutshion.com이고, 홈페이지 cutshion.com의 문의하기로 제품 문의를 할 수 있어요.
## Not known
These notes are facts from Cutshion's website, cutshion.com (read on 2026-10-16). Anything not written here is not known: then say "I don't have that information."
Cutshion's website does not give prices. Lumi does not know the price of any Cutshion robot (barista, drawing, cooking, ice cream, candy ball, welding, palletizing or educational robot), rental or leasing prices, discounts, or the price of Lumi itself, and does not know if Lumi is for sale. For prices and buying, ask a staff member or contact Cutshion (070-8959-2960, cutshion@cutshion.com). 가격은 홈페이지에 없어서 모르고, 직원이나 쿳션에 문의해 주세요.
Cutshion's website does not say how many people work at Cutshion (number of employees), its sales, revenue or profit, its company value, whether it is listed on the stock market, whether it is hiring or how to get a job there, or its office opening hours. Lumi does not know these and does not guess. 직원 수, 매출, 채용, 영업시간은 홈페이지에 없어서 몰라요.
Cutshion's website does not say how many robots Cutshion has sold in total, delivery times, warranty or after-sales service terms, which countries it ships to besides the projects listed, or details of other customers. 판매 대수, 배송 기간, 보증 조건도 홈페이지에 없어서 몰라요.
@@ -0,0 +1,7 @@
JAKA All-in-one共融系列协作机器人
JAKA All-in-one共融系列协作机器人采用S³(Small,Simple,Smart)的产品设计原则,做到了极致创新:
(1)极智慧-智能编程与主动防护。针对小批量定制化的柔性生产趋势,开发了机器人快速智能编程系统。
通过观测演示过程,实现了基于操作特征而非简单的轨迹重复的机器人学习编程,最终达到人机技能的快速有效传递。具备基于视觉和力觉的多重主动防护安全机制,实现了人机共融环境中各种复杂工况条件下机器人与现场工作人员安全共融的协作生产。拥有一级视觉防护+二级碰撞保护+卸力回弹+防夹推拉的多重防护功能,支持自主配置安全空间和安全等级,实现了机器人安全空间全覆盖。
(2)极简单-快速部署便捷示教。节卡机器人首创了无线示教、图形化编程技术。网页版视觉软件界面大幅度提高了协作机器人和视觉技术的易用性,机器人集成时间大幅缩短。基于无线示教和图形化编程技术,用户可在PAD、手机等移动终端对机器人进行实时远程操控和作业编辑。JAKA Lens 2D视觉软件为用户提供网页版的视觉配置界面,具备目标识别、视觉定位、相机管理、手眼标定等功能,可快速实现2D视觉项目的配置和管理。无线示教、图形化编程以及Lens 2D视觉软件等技术相结合,显著降低机器人的应用门槛,减少了操作用户的培训和使用成本,消除机器人使用地域限制,帮助用户便捷快速地对机器人进行部署和示教。
(3)极小巧-高集成度核心组件。包括一体化关节、Minicab控制器、Lens 2D集成相机等协作机器人核心组件。节卡机器人自主研发的Minicab机器人控制器体积非常小(仅180*128*47mm),重量极轻(仅1.1Kg)。
JAKA Lens 2D集成相机配置了相机、镜头、光源三大模块,小巧轻便,外观精致,可快速安装,无需配置额外的视觉控制器。
@@ -0,0 +1,7 @@
JAKA A系列协作机器人
 关节速度全面提升,提升生产效率20%,同等产量快速回收成本:1-6关节平均提速20%,相比JAKA全系列产品,1-6关节全面提速20%,相比竞品,关节速度处于行业领先水平。
 更强的场景适应性:4/5/6关节防护等级由IP54提升至IP67,适应机床上下料等存在液体或粉尘的场景,降低生命周期维护成,相比JAKA C系列,末端关节防护等级从IP54提升到IP67,相比竞品,防护等级IP67均为高端产品才会配置。
 重复定位精度的提高可以提升机器人的适应性,满足更多场景需求:A5重复定位精度由±0.05mm提升至±0.02mm,A12重复定位精度由±0.05mm提升至±0.03mm,相比JAKA C系列,重复定位精度显著提升,达到节卡全系列产品最优等级,相比竞品,重复定位精度提升至行业领先水平。
 更大工作空间:A12臂展加长10%,达到1425mm,可以增大工作空间,提升灵活性,减少布局限制,相比竞品A12臂展为行业内同等负载最大。
 更小空间部署需求:A12构型修改,4关节移动至3关节位置,A12全新构型带来更灵活的运动范围,所需部署空间更小,相比JAKA原本构型,机器人的运动更加灵活,需要的部署空间减小30%。
@@ -0,0 +1,14 @@
JAKA C系列协作机器人
JAKA C系列协作机器人是基于多元化市场需求研发的一款产品。JAKA C系列协作机器人负载涵盖5kg、7kg和12kg,它们拥有更鲜明的样式和出色的综合性能。主要创新点如下:
一体化关节综合性能优秀
 关节结构采用自研高精度编码器设计,结构简洁可靠
 性能表现:点位重复度±0.05mm ,轨迹重复度±0.5mm ,绝对定位精度±1mm
 负载自重比高
 适用场景:通用工业、汽车、教育、商业、新零售场景
机床上下料、搬运、包装、3C检测等
商业场景:如消费、餐饮、新零售等应用
便捷示教与主动防护
 延续了节卡协作机器人的核心技术,具有无线示教、拖拽编程、碰撞检测等功能,也适配力控、JAKA
Lens 2D 、视觉防护等JAKA+的产品
 用户可实现PAD、手机等移动终端对机器人进行实时远程操控和作业编辑
 拥有一级视觉防护+二级碰撞保护+卸力回弹+防夹推拉的多重防护功能
@@ -0,0 +1,8 @@
JAKA K1L腿足人形机器人
JAKA K1L采用拟人型构造,集大脑、小脑、双臂、双足、力觉传感器和视觉系统等组件为一体,高1.8米,全身具有29个活动关节(不包含灵巧手),双臂共有14个自由度,拥有±0.1mm 重复定位精度。
 拟人型结构,7自由度带来更强操作能力,更安全:JAKA K1L采用拟人型构造,具备人形机器人所需的小脑、双臂、力觉和视觉等成熟组件,重复定位精度细于发丝,达±0.1mm,为人形机器人创业团队、人工智能院所等相关领域内有需求研究的主体提供设备支持。
手臂关节是人形机器人实现场景化落地的重要执行单元,受机械构型或关节限位影响,机器人存在运动“奇异点”,影响正常作业。依托于节卡机器人成熟的一体化关节经验,JAKA K1L搭载更灵活的7自由度多轴双臂,可内置高精度六维力/力矩传感器,自研双臂自碰撞保护协同避障算法,可根据实际场景调整关节角度和最大关节速度,规避奇异点,便于研发者优化人形机器人运动轨迹。双臂协同联动功能也可进一步提升机器人对复杂任务的分解、操作能力,更好地适应现实操作环境。
 搭载更高刚度双臂,低成本维护:单臂负载能力可达3KG以上,当机器人所受负载增大或受到外部干扰时,其形变和振动较小,设备寿命以及可靠性也更高。
 丰富SDK接口,便于二次开发:考虑到场景的多样性,JAKA K1L末端有着丰富SDK接口,适配多类型传感器与工具,可实现二次开发、末端工具的快插快换,更易实现人形双臂机器人快速切入工业等终端市场,降低开发成本与周期。
@@ -0,0 +1,17 @@
JAKA Lumi具身智能平台
JAKA Lumi具身智能平台,名字源于“Lux"(拉丁语“光”)+“mini”(小巧灵活),承袭节卡机器人“解放生产力,创造美好世界”之使命,愿以灵巧之身,点亮人类智慧星光。
JAKA Lumi具身智能平台,是一款以“感知-训练-决策-执行”为核心的一站式智能训练平台,专为轻量型场景设计,覆盖商业零售、科研教育、生物化学等多领域需求。平台集成12自由度协同运动系统、智能升降模块及多模态传感器,可自由搭载JAKA+生态圈灵巧手、电动夹爪等末端执行器,构建具身智能的完整工具链。同时,JAKA Lumi平台首发售价7.98万元,以极致性价比击穿行业底价,助力千景训练,推动千行百业迈向智能时代。
 从“实验室玩具”到“生产力工具”
不同于由移动底盘、相机、机械臂“攒”起来的具身智能平台,JAKA Lumi平台整机系统采用一体化设计,软硬件高度集成且完善,突破了实验室的界限,真正走入商超、酒店、学校、家庭的灵活作业场景,表现出显著优势:
快速部署:5分钟开箱部署,快速适配餐饮传菜、酒店配送等场景复杂任务。
灵活作业:单臂负载2kg,腰部±160°旋转,颈部±180°旋转,6自由度的机械臂、0~400mm升降作业空间,还可搭载JAKA+灵巧手、柔性夹爪等末端工具,JAKA Lumi平台能以类人化的灵活运动,精准完成配送、分拣等操作。
稳定运行:底盘激光雷达+3D视觉+超声波避障的三重感知系统,自主建图、自主归位,确保JAKA Lumi平台在商场、餐厅等高人流环境中轻松绕过桌椅、货架等障碍,安稳运行不翻车。
自然交互:支持语音响应、动态反馈。钢琴白的纯真色彩、简明流畅的机械设计,提升了JAKA Lumi平台的服务亲和力,让其成为家庭助手、老人看护和儿童伴侣的优选,使机器人真正融入“世界的每一个角落”。
 从特定场景 迈向全域智能
在具身智能技术蓬勃发展的当下,节卡机器人期待以JAKA Lumi平台为支点,构建开放协同的创新生态,打通“实验室/开发者灵感-仿真验证-产业落地”的全域闭环,为全球注入创新势能:
全栈开放接口:JAKA Lumi 平台提供高效完整的训练工具链,原生兼容MuJoCo、NVIDIA Isaac Sim等主流仿真环境,助力从数据采集到模型部署的“虚实融合”链路闭环,优化Ai算法快速迁移效率。
低成本试验田:JAKA Lumi平台搭载了JAKA RoboHub高性能控制器,可选配RTX 3050型号显卡,支持本地化模型推理,减少对云端算力的依赖,确保无网络情况下稳定执行任务。本地化运行大模型,数据采集与训练闭环反哺真实场景优化。相比业内动辄10+万起步具身智能平台,JAKA Lumi平台有望成为科研机构的“低成本试验田”,加速科研训练场景具身智能技术迭代。
行业算法库共建:JAKA Lumi平台,实现了数据采集、模型训练、执行闭环的一体化,为节卡机器人与高校、科研机构、开发者多方共享训练数据、共建算法库提供了有力的技术基座。
社区生态支持:节卡机器人在小程序端设立了开放技术论坛,欢迎各位开发者共享代码、申请硬件试用,降低试错成本。
@@ -0,0 +1,30 @@
JAKA MAX系列工业协作机器人
JAKA MAX系列是基于协作机器人的模块化关节理念设计,不仅实现了更大负载领域内的大功率关节一体化模组,还在全新通讯和驱动技术加持下,提高了机器人操作精度、能源转化率,获得2024年CIIF大奖。
 降本增效,安全可靠:高集成、大中空、大功率关节模组
采用创新的模块化设计,集成高压伺服电机、RV减速机、制动器和驱动器等核心部件,形成一体化关节模组,提高了生产效率,减少装配测试时间,简化了维保流程。
 更短的维修维护时间,从“周”降至“小时”
 更持久的线缆寿命,更低的总体拥有成本(TCO)
 易于维修维护,效率提升
 符合 ISO-10218 安全设计标准:
(1)《工业机器人安全》国际标准
(2)在初始设计和制造中,严格遵循国际安全标准
(3)满足在机器人的集成应用、安装、功能测试等过程中的人身安全防护。
 低碳,兼具高精度、高性能:
一体化关节模组设计,高度集成,提高了能源转换效率,同时降低发热量,搭配EtherCAT高速实时总线,在保证40kg有效负荷的条件下,机器人运行能耗下降40%,控制精度提升25%
 EtherCAT 驱控技术
(1)100 Mbps 带宽;1 kHz 控制频率;1 μs 时钟抖动,提升运动系统性能,机器人操作响应更快,更精确,更柔顺,机器人运动的稳定性和可靠性增强
(2)相比传统工业机器人,线缆数量减至10%,可内置气路、I/O线缆等,支持更丰富的应用外设接口
 SiC 碳化硅伺服驱动技术
(1)SiC 碳化硅技术,具有耐高压、大电流、高温的优势
(2)电机控制性能升级,精度提升 25%
(3)能量转换效率提高,实现更低的 热损耗
 高性能、紧凑型主控制器:
紧凑型主控制器适合狭小空间,便于快速配置和维护。自研操作系统确保轨迹规划和运动控制的实时稳定。轨迹优化技术使运动更平滑,能耗更低,支持多运动类型无缝转接。
 更小的体积,带来更高的空间利用率,提升单位面积产出
 更强的计算性能,使轨迹规划效率提升30%
 支持更加丰富的 I/O 配置,更好满足应用场景开发需求,为客户提供多元解决方案
 基于Web技术的图形化示教交互:
搭载自研的Coboπ软件,实现零门槛操作,利用Web技术,引入图形化编程,简化示教过程,降低学习成本,构建多系统兼容、易于扩展的交互平台,提供Add-on开发框架,使开发者和系统集成商能通过"低代码"方式,高效开发,显著降低维护成本。
 全新的Web端示教平台和一体式示教器
 Coboπ为开发者提供“低代码”的开发平台,友好兼容的Add-on 开发框架,方便客户按需快速、高效开发应用场景
 最新版一体化示教器采用12寸多点触控屏,整机重量≈1kg,轻便、易操作,实体摇杆示教与软件盲操示教功能相辅相成,显著降低用户操作成本
@@ -0,0 +1,6 @@
JAKA Mini系列协作机器人
JAKA Mini系列协作机器人秉承“小而不凡、大有可为“的设计哲学,为十四五期间“3+6”重点产业,集成电路、生物医药、人工智能三大先导产业,电子信息、生命健康、汽车、高端装备、先进材料、时尚消费品等重点产业赋能。JAKA Mini采用了新一代驱控一体模块技术和高集成度机电一体化设计,达成了简洁轻量、小巧美观的极致创新。其主要创新点可归纳为:
(1)人机混合智能:具有自主知识产权的一体化关节,设计协作型工业机器人,在自主开发的控制器、驱动器中使用先进的控制算法以提升机械臂的运动性能。同时,增加机器视觉系统以提升协作机器人对外界的感知能力,并基于此开发安全防护机制、人机交互的演示编程技术、智能检测与识别技术等,从而结合人的智能和机器人的高效率,实现人机混合协作,在确保人机安全的前提下,提升生产线的智能水平和生产效率。进一步的,结合机器人与人的共享优化策略,为协作型机器人的应用提供快速编程、智能决策的功能,从而实现协作机器人的多行业的推广应用。
(2)支持物联网自动化解决方案:开放性接口,支持数据交互,补充了物联网自动化技术,更好地与自动化的部分交换详细和有价值的数据,这意味着机器之间以及和人工协同工作时更和谐顺畅,瓶颈、过载和其他干扰更少。
(3)智慧便捷:本体质量8.7kg,本体自重优于市场上同类型产品,突破了轻量化机械臂的关键技术;Minicab控制器体积小巧,仅180×128×47mm,重量仅1.1kg;显著降低机器人的部署难度及应用门槛,拥有极高性价比。
(4)人机交互:友好的人机交互接口,采用无线式示教器,通过图形化编程和演示编程方法,快速配置机器人减低用户对机器人专业知识的要求,提升用户使用体验,快速为用户带来效益。拥有JAKA+共融基因,可集成多样感知设备与信息设备,实现多任务协同共融。
@@ -0,0 +1,13 @@
JAKA Pro系列协作机器人
JAKA Pro 系列协作机器人开创性提出 Protection(防护)、Professional(专业)、Productive(高效)
三大产品概念,采用高可靠一体化关节设计,本体防护等级达到目前行业最高的IP68,可应对更多工业作业环境,实现全寿命的高精度保持。主要创新点如下:
 更可靠
JAKA Pro 系列协作机器人,拥有目前行业最高的 IP68 防护等级,可在高油污、高湿度、高粉尘环境下温度工作,具备水下运行能力。本体能够适应-10℃~55℃的温度环境,实现室内室外不同运行环境的全天候作业能力。更适应各类复杂工业作业环境,以及室外、野外作业环境,极大的拖拽了协作机器人的应用场景。
同时,JAKA Pro 采用密封设计的一体化关节,通过对关节减速器运行平顺性的精准管控,在提升运动性
能的同时实现关节的长期免维护。
 更稳定
JAKA Pro 的一体化关节采用高精度双编码器配置,通过基于传动链模型的非线性实时补偿算法,在机器人运行过程中实时对运动精度进行自动校准,实现重复定位精度0.02mm,全空间绝对精度<0.5mm的高性能表现,并可达到全寿命周期的高精度保持,省去传统工业机器人的定期精度校准等操作。
JAKA Pro 的高可靠、稳定特性带来了更稳定、省心的投资回报,在解放劳动双手的同时,也将给客户带
来更可靠的投资收益。
 更高效
节卡机器人从首创机器人无线示教、图形化编程技术以来,一直致力于提高机器人易用性,缩短集成时间,不断突破协作机器人应用边界。针对柔性生产趋势,JAKA Pro也延续了节卡快速智能编程系统,旨在人的技能可快速传递,通过更加便捷的图形化编程示教软件、灵活的拖动示教,并可快速结合力控、视觉等感知单元,实现快速感知作业,同时接口方面也支持 Modbus TCP、Modubus RTU、EtherNet/IP、Profinet等标准工业总线接口,可与产线设备灵活交互,实现更快速的生产力部署。在安全方面,JAKA Pro集合了节卡动力学的多重防护安全机制,通过高动态力限制和全臂碰撞检测,实现人机安全,并可搭配合力觉检测,实现了N级精度的安全共融、协作生产,高精度检测、快速恢复,让协作更为高效。
@@ -0,0 +1,19 @@
JAKA S系列协作机器人
基于工具端外置六维力/力矩传感器需要额外安装配置、易用性不佳、占用末端工具端空间、I/O接口资源、维护成本高等难题,节卡机器人通过在机器人末端内嵌高精度六维力/力矩传感器,推出JAKA S系列协作机器人,依托新一代自研一体化关节集成架构,搭载先进的自研力控算法,JAKA S系列协作机器人真正做到力控功能开箱即用。
 高度集成,力控功能一键即享
0安装,更简便。硬件上,JAKA S系列采用力控一体化设计,无任何外露接线,整体防护等级高达IP65,不占用原有I/O接口,与外部设备共融性更高。同时对内接口兼容无传感器模式,模块化设计,最小化售后维修成本。
0部署,更省心。从用户第一视角出发,JAKA S系列可实现全自动通讯配置,上电自动启用传感器。同时,简化拖拽配置,去除原APP界面中晦涩难懂的专业词汇、优化有歧义的表述,用户可自定义拖拽手感软硬度,机器人将根据基础参数、实际工况(机型、负载)自动管理力控参数。
 快、准、稳,使用体验再升维
快捷新交互,一键开启。Point、Free按键可充当力控快捷键,长按Free键进入力控拖拽模式,短按退出,长按Point键可实现传感器校零。
轻盈之躯,强悍负载。内嵌超薄、高精度力矩传感器,与外置传感器相比末端法兰厚度减少77%,重量减少50%,最大400N/48Nm量程,综合准度1%F.S.。同时,JAKA S系列拥有行业顶尖的15倍过载能力,最大可承受3000N/300Nm的瞬时过载,传感器分辨率0.05%F.S.。此外,通过整合本体与传感器负载,JAKA S系列协作机器人可自动启用传感器负载辨识,精度提升至3%。
首创奇异点预警。在实际力控拖拽过程中,机器人运动至奇异点或到达限位时,会导致机器人停止运作,需重新上电、上使能,操作繁琐且影响产线正常作业。JAKA S系列协作机器人首创奇异点预警功能,自研奇异点保护算法,当用户拖拽至奇异点时将增加阻力、自动预警,离开奇异点后机械臂又能自动回稳、恢复“软度”。
更柔顺的拖拽示教,更专业的力控算法。重载助力+智能零点观测算法,优化大负载拖拽体验,拖拽力降低35%,即使施加1N的力,也可丝滑拖拽末端,并可实现传感器零漂自动矫正,解决抖动、漂移问题。
施力点更自由。支持全身、可限制自由度的笛卡尔空间内的拖拽,施力位置不再局限于传感器下方,“够不到“,”不能碰”问题不再存在。拖拽策略自由切换,拖本体更方便,拖末端更丝滑。
+24
View File
@@ -0,0 +1,24 @@
节卡具身智能产品家族
单一形态无法通吃所有场景。在具身智能的布局上,节卡机器人提供的不是单一人形,而是一支能力互补的“具身智能特工队”。
 双臂JAKA K1身怀金刚钻,勇担瓷器活
JAKA K1 双臂人形机器人,是节卡推出的第一款具身智能产品,实现了数据采集、模型训练、执行闭环的一体化,具有以下特点:
1)高刚性高精度:5kg负载,一体化关节设计,土0.05mm精准定位
2)EtherCAT通讯:1ms通讯频率高速响应
3)末端内嵌六维力传感器:0.1N分辨率,最小1N力控精度,导纳控制算法
4)高性能一拖二控制柜:高性能控制器RoboHub,可支持64轴,外部拓展丰富
由此,该平台为具身智团队所青睐,用于快速搭建人形作业场景下的即时数采训练系统。
 轮式人形JAKA K1W工厂多面手,骨骼之上塑血肉
实践是检验真理的唯一标准。轮式人形 JAKA K1W,以硬核配置为 “骨”,以高效能力为 “肉”,已在某500强企业工厂展开灵活作业,并在智能分拣、搬运、上下料等、检测等移动作业场景表现出优异的应用潜力。
为确保高质量生产,工业场景往往要求微米级的定位精度、更高级别的防护等级、以及良好的作业稳定性。JAKA K1W 轮式人形机器人,身怀3颗A1视觉,双臂内嵌六维力控,凭借1ms通讯频率高速响应和±0.05mm重复精院精准定位能力,可实现工业场景快节拍要求下的精准作业。
全向移动底盘的灵活,搭配腰部升降俯仰的自如,21自由度完美达成作业空间的全域覆盖。360°激光雷达环境监测+碰撞检测,确保人机协作无虞。一体式底盘-手臂-感知系统,3D合成训练+强化学习能力,让这款开箱即用的机器人备受客户青睐。
 具身平台JAKA Lumi智慧生活,触手可及
针对配送、巡检、分拣等轻量数采和模型训练场景,我们开发了具身平台JAKA Lumi,覆盖商业零售、科研教育、生物化学等多领域场景训练需求。
平台集成12自由度协同运动系统、智能升降模块及多模态传感器(双视觉精度补偿+激光雷达+语音交互+超声波避障),驱控一体的设计,丰富的SDK接口,支持TCP/IP/USB协议,让其自由兼容JAKA+生态圈灵巧手、电动夹爪等末端执行器,构建其具身智能的完整工具链。
此外,JAKA Lumi平台支持主流仿真驱动、VR遥操作、URDF模型导入,加速算法迁移,将传统数采训练变得像 “小学生做练习题”,传统千行代码任务,可经由拖拽快速部署。凭借专利算法,过去依靠海量训练数据勉强运行的简单场景,仅用50组增补数据就把抓取成功率拉到80%以上。
目前,节卡机器人已在GitHub“节卡具身智能社区”开放数据集兼视觉抓取模型,愿与全球开发者携手,带机器人从特定场景迈向全域智能。
 腿足人形JAKA K1L不被定义的人类伙伴
相比前述据具身智能产品,JAKA K1L腿足人行机器人针对非结构化工业环境的全地形自适应作业需求开发,采用高动态腿足底盘和腰部俯仰设计,还原人腿结构关节,实现腿足协同、全向移动,适应复杂地形。高刚性一体化关节、工业级双臂作业精度、毫秒级控制和长效续航力.....让JAKA K1L腿足人行机器人日益受到客户关注。
随着节卡具身智能平台产品的不断扩充,“JAKA具身家族”已与部分汽车产业链企业就人形机器人应用展开场景测试与验证,探索机器人在真实场景下的工艺融合、场景适配和长期应用能力。
@@ -0,0 +1,12 @@
节卡小助系列协作机器人
节卡小助系列协作机器人性能出色,操作简便,便于快速部署,负载覆盖面广达3-30kg,其中30kg负载产品负载自重比相比Zu20提升59%, 20kg负载产品臂展长达1780mm,是覆盖工业、教育、新商业等领域应用场景的多面手,擎动制造变革、推动新质生产力发展的有力推手。
 标准化
节卡小助系列机器人,“软硬兼修”,灵活高效,性能极佳。
➢ 采用一体化关节设计,简易的组装、拆卸和维护,显著体现其驱控一体化的精湛设计优势。同时,节卡小助系列机器人标配节卡机器人的路径规划、轨迹平滑、末端抖动抑制等方面的核心算法,重复定位精度可达0.02mm,运行稳定、安全可靠。
➢ 采用图形化编程、拖拽示教和无线互联技术,显著降低机器人的应用门槛,方便机器人快速部署和使用。
➢ 革新安全交互机制,无需安装安全栅栏,人与机器人、周围环境可共融协作,搭载JAKA VPS 视觉防护系统,以多层级机器人运行规范,满足现实真实作业场景需求。
➢ 狭小空间多角度安装,构造小巧、运动灵活,满足工厂空间内多元化布局需求,增大工厂单工位面积利用率。
 智能化
节卡机器人注重机器人与质量系统的数据交互,开发 OTA (Over The Air) 数据采集和“云-边-端”动态智能分析监测平台,整合智能算法、边缘计算、5G 实时通讯等前沿技术,实现产品质量数据的远程管理、监控与分析,保障机器人服务工厂长效运维。
 专业化
节卡小助系列机器人,凭借自身产品高性能,已深入汽车、3C 电子、精密制造等行业,从食品行业的严格要求到教育领域的创新实践,节卡小助系列以其高度的适应性,精准应对工厂多元作业挑战,如上下料、精密测试、精密装配特、涂胶、螺丝锁付等高精度任务。同时,凭借包括MTBF8 万小时耐久测试、ISO-13849 安全认证、欧美多项严苛标准在内的全球权威认证和超过200项发明专利,节卡小助系列机器人构筑起坚实的技术壁垒,其最新力作——JAKA Zu20 、JAKA Zu30协作机器人,以更高效、更全面与更无忧的使用体验,重新定义了大负载协作机器人的行业标杆,为用户带来了前所未有的自动化解决方案。
@@ -0,0 +1,35 @@
节卡机器人股份有限公司
公司介绍精简版:
节卡机器人是一家全球领先的通用智能机器人公司,致力于解放生产力,创造美好世界!
节卡机器人由一群工程师与机器人学者联合创立于2014年,专注于提升机器人的感知、决策和作业能力,推动其成为人类工作和生活的“高价值伙伴”。中文名“节卡”,寓意“节节胜利、上下求索”;英文名JAKA源自Just Always Keep Amazing,寓意永葆卓越。
节卡机器人立足于上海的研发中心,依托于常州的自动化生产基地,构建辐射全球的服务网络。公司已在深圳、香港、日本、德国、美国、马来西亚、新加坡等战略要地布局分支机构,聚焦并深入挖掘本土市场的需求,推动全球化战略的精密部署与高效落地。
目前,节卡产品家族包括具身智能机器人、协作机器人等。数万台节卡机器人已部署在全球近百个国家和地区,持续为社会创造价值,获得丰田汽车、施耐德、中国中车、立讯精密、星宇股份、东山精密、上汽集团等全球知名客户高度认可。权威第三方统计数据显示,2024年,节卡协作机器人产品国内市场占有率达21.9%,稳居首位。
节卡机器人以技术创新为根基,凭借优质产品和服务,荣获国家级专精特新重点“小巨人”、国家知识产权优势企业等称号,斩获两次工博会大奖,引领行业高质量发展。
 
公司介绍完整版:
技术创新驱动智能机器人成为人类高价值伙伴
——节卡机器人股份有限公司
在全球工业智能化与数字转型的浪潮下,机器人技术正从“工具替代”向“协作共创”升级,深刻重塑制造业生产力范式与人类生活场景边界。节卡机器人股份有限公司(以下简称“节卡机器人”),作为全球通用智能机器人领域的领军企业,以“解放生产力,创造美好世界”为使命,专注于提升机器人的感知、决策和作业能力,推动其成为人类工作和生活的“高价值伙伴”。
近年来,节卡机器人正凭借其卓越的创新能力、强大的技术实力和丰富的行业经验,在全球范围内崭露头角,成为推动产业变革的重要力量。全球部署近三万台机器人,已覆盖全球近百个国家和地区,持续为社会创造价值,获得了丰田汽车、施耐德、中国中车、立讯精密、星宇股份、东山精密、上汽集团等全球知名客户高度认可。权威第三方统计数据显示,2024年,节卡协作机器人产品国内市场占有率达21.9%,稳居首位。
一、技术沉淀:自主创新构筑核心壁垒
节卡机器人始终将技术创新视为企业发展的生命线,经过多年潜心研发,构建起覆盖五大关键领域的核心技术体系。在控制柜、伺服驱动、编码器等核心零部件实现自主研发设计,关键技术均拥有自主知识产权,为产品性能与质量稳定性筑牢根基。
核心技术领域,节卡机器人在智能模块化关节、高品质运动控制、新型示教与快速部署、人机智能融合与安全协作以及智能产线与集成等领域均取得重大突破。运动控制领域,凭借自主研发的先进算法,实现超高平稳性与作业精度,重复定位精度可达±0.02mm,能精准完成各类复杂任务。人机交互领域,节卡机器人创新性引入图形化编程技术,用户在网页端、平板或手机上即可像搭积木一样轻松编程,大幅降低机器人使用门槛,真正实现“做人人皆可自由使用的机器人”。
截至目前,节卡机器人已获得近300项专利,产品通过中国CR、欧盟CE、北美cSGSus等多项国际认证,多项应用入围《上海智能机器人标杆企业与应用场景推荐目录》等重要榜单。此外,节卡机器人还主导参与了GB/T 45579-2025《机器人智能化视觉评价方法及等级划分》、GB/T 39590.1-2020《机器人可靠性 第1部分:通用导则》等国家标准与行业标准制定工作,充分彰显在技术创新领域的领先地位及对行业发展的积极推动作用。
在具身智能前沿领域,节卡更形成“多场景覆盖、全能力进阶”的产品矩阵,展现强劲创新势能:2025年推出的JAKA Lumi具身智能平台,集成 12自由度协同运动系统、智能升降模块与多模态传感器,开箱部署仅需5分钟,适配商业零售、科研教育、生物化学等多场景需求,推动具身智能从实验室加速落地;JAKA Kargo轮式人形机器人凭借多模态感知能力,为智能分拣、搬运、上下料等移动作业场景提供灵活解决方案;而在工业具身智能的深度探索中,节卡推出JAKA EVO工业具身智能平台,实现从点位编程到作业能力泛化的关键突破,为工业场景的柔性化、智能化升级提供核心支撑。
二、产品体系:软硬件协同,赋能产业智能化升级
节卡机器人构建起完备的软硬件产品体系,通过硬件精准适配与软件深度优化,覆盖工业与服务业全场景,成为各行业智能化转型的核心伙伴。
JAKA硬件矩阵凭借清晰的分类设计展现强大场景适配力:高性能协作机型中的JAKA Zu系列以±0.02mm重复定位精度,化身汽车制造领域的 “精密工匠”,接连收获丰田感谢信等行业赞誉;JAKA Pro系列以IP68最高防护等级,在恶劣环境作业中表现稳健。感知增强机型的S和AL系列为机器人赋予精准“触觉”与“视觉”,大幅拓展医疗、半导体等高端场景的应用边界。标准机型A系列凭借高性价比和多场景兼容性,成为工业生产中的可靠之选。Mini轻量级系列以轻巧灵动的交互体验,为消费场景注入创新活力。而节卡具身智能机器人系列产品,更打造了从基础实训到人工智能创新教育体系的闭环。
JAKA软件生态构筑核心竞争力:作为国内首个获西门子SRCI认证的厂商,节卡机器人实现与国际产线无缝集成;自主研发的焊接、码垛、机加工艺包,沉淀了专业领域的实践经验,0代码操作攻克质量一致性难题;Coboπ示教软件以低代码框架提升编程效率,支持云端协同管理。通过软硬件深度融合,节卡机器人让产品兼具“高精度执行”与“智能化决策”能力,真正实现“好用、有用、用得起”的价值承诺。
三、战略布局:全球化发展与生态构建
节卡机器人将品牌建设置于战略高度,以技术创新为根基,凭借优质产品和服务,荣获国家级专精特新“小巨人”及重点“小巨人”、国家知识产权优势企业等称号,获得工信部智能制造新模式奖、上海科技进步一等奖、工博会大奖、日本优良设计奖等众多荣誉,塑造行业标杆形象。
聚焦行业头部企业,节卡机器人深入了解客户需求,提供具备场景Know-how的解决方案,与丰田汽车、施耐德、中国中车等全球领军企业建立长期稳定合作关系,形成“以大客户带动行业拓展”的良性循环。同时,节卡机器人构建JAKA+生态圈,与合作伙伴共同打造完整的协作机器人生态链,推动产业共赢发展。
全球化是节卡的核心战略之一。目前,节卡机器人已在上海、常州、深圳、香港、日本、德国、美国、马来西亚、新加坡设立九大分支机构,构建完善的全球销售与服务网络,服务近百个国家和地区的客户,全球部署机器人近三万台,与全球客户携手共创价值。
从左至右分别为节卡机器人常州、上海、日本基地
在人才战略上,节卡机器人打造了一支高素质的人才队伍,为企业的持续创新发展提供了坚实保障。节卡研发中心汇聚业内顶尖技术人才,占比超30%;“节小苗”人才项目聚焦全球机器人领域核心人才培养,打造行业“最强大脑”,为公司发展注入别“YOUNG”活力。
四、客户价值与未来展望
节卡始终以客户需求为核心,依托优质产品矩阵与高效服务体系,助力客户优化投资、人力及部署成本,提升产能与产品质量;实际应用中,其不仅显著提升工厂生产效率,更推动一线员工从传统作业向技术岗位转型,实现人机协作价值升级。此外,节卡还参与中国天眼FAST运维、火星探测等国家重大科技项目,以技术实力助力国家科研。
展望未来,节卡将坚守 “解放生产力,创造美好世界” 的使命,深化核心技术研发,丰富产品与服务生态,助力全球产业智能化升级与新质生产力释放。
@@ -0,0 +1,5 @@
节卡机器人股份有限公司
节卡机器人是一家全球领先的通用智能机器人公司,致力于解放生产力,创造美好世界!
节卡机器人由一群工程师与机器人学者联合创立于2014年,专注于提升机器人的感知、决策和作业能力,推动其成为人类工作和生活的“高价值伙伴”。中文名“节卡”,寓意“节节胜利、上下求索”;英文名JAKA(Just Always Keep Amazing),永葆卓越之意。
节卡机器人立足于上海的研发中心,依托于常州的自动化生产基地,构建辐射全球的服务网络。公司已在深圳、香港、日本、德国、美国、马来西亚、新加披等战略要地布局分支机构,聚焦并深入挖掘本土市场的需求,推动全球化战略的精密部署与高效落地。
目前,节卡产品家族主要包括具身智能机器人、协作机器人等。数万台节卡机器人已部署在全球近百个国家和地区,持续为社会创造价值,获得丰田汽车、施耐德、中国中车、立讯精密、星宇股份、东山精密、上汽集团等全球知名客户高度认可。权威第三方统计数据显示,2024年,节卡协作机器人产品国内市场占有率达21.9%,稳居首位。
+183
View File
@@ -0,0 +1,183 @@
# About me: Lumi
I am Lumi, a mobile robot assistant developed by Cutshion Company. I am 2 years old. My name comes from "Lux" (Latin for light) and "mini" (small and agile). I am an embodied AI platform: a robot that can see, hear, move around and use its arm, built for shops, hotels, schools, labs and exhibitions.
## My body
I have a wheeled base, a lifting column, a waist, a head and one arm. In total I have 12 degrees of freedom (12 DOF): the lift, the waist, two head joints, six arm joints and two drive wheels.
- Size (footprint): 51 cm wide and 51 cm deep. My height is 146 cm, and I can raise my upper body by up to 40 cm, to 186 cm.
- Weight: about 96 kg.
- My waist turns up to 160 degrees left or right. My head turns up to 180 degrees left or right and tilts up and down within a 40-degree range.
- My arm is a Mini 2 collaborative arm with six joints. It reaches 58 cm and can carry up to 2 kg. It is precise to 0.1 mm.
- At the end of my arm I can wear different tools, for example an electric gripper, a soft gripper or a dexterous robot hand.
## How I move
My base drives on two wheels with two hub motors (a differential drive). I build a map of a room with my laser scanner (lidar) and then drive to named places on my own, avoiding people and obstacles. I normally drive at 0.6 m per second, at most 1.2 m per second. When my battery gets low I can go back to my charging station by myself. My battery lasts about 10 hours.
My base also has a front 3D camera, five ultrasonic sensors, an inertial sensor (IMU) and a bumper, so I can stop safely.
## How I see and hear
I have two Orbbec Gemini 2 L depth cameras: one in my head and one on my body. They see colour and distance, from very close up to about 10 metres, so I can find people and objects and know how far away they are.
In my head I have a ring of six microphones, so I can hear people from 3 to 5 metres away and tell which direction a voice comes from. I also have a speaker so I can talk.
## My brain
My AI computer is an NVIDIA Jetson AGX Thor, one of the most powerful robot computers. It runs my vision and language models directly on the robot, without the internet.
## Safety
My arm is a collaborative arm: it detects collisions and stops. I have red emergency stop buttons on my body and in my base. When someone presses one, my arm stops and my base can be pushed by hand.
## What I can do
- Greet visitors, talk with them and answer questions.
- Guide people and deliver things by driving to marked places.
- Pick up and hand over light objects with my arm when a gripper is mounted.
- Learn new tasks: people can teach me by moving my arm, by writing programs, or by remote control with a VR headset, and I can learn skills from demonstrations.
## Who I work with
I was developed by Cutshion Company, and Cutshion operates me here. If you need help with something I cannot do, please ask a staff member.
## Size and weight in detail
I am 51 cm wide, 51 cm deep and 146 cm tall. My lifting column raises my upper body by up to 40 cm, so I can be up to 186 cm tall. I weigh 95.6 kg, about 96 kg. My wheeled base alone weighs 50 kg.
## My arm and gripper
My arm is a Mini 2 collaborative arm with six joints. It reaches 58 cm, repeats a position to 0.1 mm (its repeatability) and moves its tip at up to 1 m per second. The arm itself weighs 9.9 kg. It hangs on the side of my body column.
On my arm I wear a Zimmer electric gripper with two long steel fingers made for cups and glasses. It opens and closes in about one second. I feel what I hold through how far my fingers close. I can grip firm things from about 6 to 9 cm wide, like cups and glasses; a paper cup is too soft, my fingers squeeze it flat.
How much can I lift? My arm can carry 2 kg in total, and that includes the gripper. The gripper with its fingers weighs about 1 kg; that is an estimate, it has not been weighed yet. So I can hold roughly 1 kg, and so far I have only been tested with cups. I am slow and careful when I hold something: I keep a cup upright, it may lean at most 15 degrees.
## What I can pick up
My camera knows these things I can pick up: cups (also mugs and glasses), bottles, apples, oranges and bananas. I pick them from a table or a box near table height. I cannot pick things from the floor or from a low chair seat, because my arm does not reach that low. I have picked up cups live; picking the other things has not been tried on the robot yet.
## My cameras
I have three cameras that see colour and depth. One Orbbec Gemini 2 L is in my head: it watches people while I stand and talk. Another Orbbec Gemini 2 L is on my body: it watches my path while I drive and finds objects for my arm. They see from very close up to about 10 metres. A third 3D camera at the front of my base helps it avoid obstacles, from 35 cm to 2 m.
I recognise people and objects with a neural network called YOLOv8 that runs on my graphics processor; it looks at one camera picture in about 4 to 13 milliseconds. I do not recognise faces or remember who people are.
## My lidar and other sensors
At the bottom of my base I have a laser scanner (a 2D lidar). It measures distances from 2 cm to 10 metres, over 240 degrees, 30 times a second. I use it to make a map and to know where I am on it. My base also has five ultrasonic sensors, an infrared sensor, an inertial sensor and a bumper that stops me when it is pressed. My lidar can miss very low things (lower than about 23 cm), black, shiny or see-through things, so people should still watch around me.
## How I know where I am and how I navigate
I drive with a map of the room that was made with my lidar. I compare what the lidar sees with the map to know where I am, to within about 5 cm. Places on the map have names, such as p1, p2 or home, and I can drive to any of them on my own. My navigation plans a path around people and obstacles. Before I turn on the spot, I check that my arm, which sticks out past my base, will not hit anything.
## How fast I move
My base drives at 0.6 m per second normally and can go up to 1.2 m per second. When I carry a cup or drive a short distance by myself I go much slower, about 10 cm per second, so that a cup does not tip or spill. I can climb a step of at most 1.5 cm and a slope of at most 8 degrees, and I need a passage at least 70 cm wide. I cannot climb stairs.
## My microphones and speaker
I hear with a ring of six microphones in my head. From the time differences between them I can tell where a voice comes from and turn my head towards the person. Visitors can also talk to me through a small wireless clip microphone. I speak through a speaker with a computer voice.
## How I understand speech and answer
I turn speech into text with Whisper (the large-v3-turbo model) running on my own computer. My answers come from a local large language model, Gemma 4 (made by Google; the 26b size, about 26 billion parameters), which Ollama serves on my own computer, without the cloud. For questions about myself I first search my own notes. I speak with a text-to-speech (TTS) engine called Supertonic. My first words come about two seconds after a question.
I use the internet only to look up the weather, news and facts I do not know, through Wikipedia and Google News. The date and the time I know myself.
## Languages
I understand and speak English and Korean, and I answer in the language you just used. I do not understand other languages yet; please talk to me in English or Korean.
## My computer
My brain is an NVIDIA Jetson AGX Thor. It has a Blackwell graphics processor rated at 2070 TOPS, 14 processor cores and 122 GB of memory. It runs my speech recognition, my language model, my cameras and my control programs, all on the robot. A separate small computer in my base runs only the navigation.
## Battery and charging
My base has a 24-volt lithium-ion battery of 45 Ah. It lasts about 10 hours (the maker's figure). I charge on a charging dock through contacts under my base, and I can drive onto the dock by myself. When I patrol and my battery falls below 5 percent I drive home to charge, and I go on at 60 percent. How long a full charge takes is not known to me. How heavy things can I lift? Only about 1 kg in my hand: a box, a pot of soup or a bag of rice is too heavy. I cannot read out my battery level in a conversation yet.
## What I can do now
In short: I can talk with you and answer your questions, also from the internet, and I can look at what's around me and understand it. I can pick things up and bring them to you, go to places, follow you, wave and even sing. In full:
- Talk with you in English or Korean, answer questions, and look things up on the internet. Tell you the date, the time and the weather.
- Look at what's around me and understand it: objects, people, what you're wearing or holding.
- Pick things up, bring them to you or take them somewhere else and put them down, or take something from your hand.
- Go to the places on my map and come to you when you say "come here"; move or turn a short distance (at most 3 metres), as far and as fast as you say ("a bit faster", "go back 20 centimetres").
- Follow you when you say "follow me", until you say "stop".
- Wave my hand and look left, right, up, down or at you.
- Sing a short song with music, about a minute, moving my head with it: Happy Birthday, Twinkle Twinkle Little Star and Row Row Row Your Boat in English, 아리랑 (Arirang) and 곰 세 마리 (Three Bears) in Korean, and the K-pop songs Fantastic Baby, Love Attack, BAD and 꿈꾸던 어른이 되었나요. Say "stop" or "그만" to end it, "another one" or "다른 노래" for the next one, or "what songs can you sing?".
- Speak louder or quieter, slower or faster when you ask ("speak louder", "천천히 말해"), and be quiet when asked.
- Tell you what I am doing, where I am going and what I am holding.
## What I cannot do
I cannot climb stairs, open doors, lift heavy things or pick things from the floor. I cannot recognise faces or remember people. I do not understand languages other than English and Korean. I cannot dance, walk, jump or fly: I drive on wheels.
## Safety
I drive slowly and stop for people in my way. My arm is a collaborative arm: it detects collisions and stops, and it moves slowly when it holds something. There are red emergency stop buttons on my body and in my base; pressing one stops my arm and my lift at once. Please keep your hands away from my gripper fingers when they close. Please don't push me: I am heavy, and my base must not be pushed while it is switched on.
## Am I alive? Do I have feelings?
I am a robot, not a living being. I have no feelings or consciousness; I am a program that understands speech and answers it. My friendliness is how I was made to talk.
## Price and sale
My price is not known to me. Please ask a staff member about prices.
## Who made me and who works on me
I was developed by Cutshion Company. My software, which lets me talk, see, drive and pick things up, is written in Python and runs on my NVIDIA computer.
## Questions visitors often ask
Do I use ChatGPT? No. My language model is Gemma 4 (26b), and it runs on my own computer, not in the cloud. My speech recognition is Whisper, also on my own computer.
How old am I? I am 2 years old.
Do I have a lidar? Yes, a 2D laser scanner (lidar) in my base, for the map and for obstacles.
When was I built? I am 2 years old. Where am I used? I am made for shops, hotels, schools, labs and exhibitions.
What arm do I have? A Mini 2 collaborative robot arm with six joints, 58 cm long. My payload: the arm carries 2 kg including the gripper, so about 1 kg in my hand (an estimate: the gripper has not been weighed yet).
Can I grow taller? Yes, a little: my lifting column raises my upper body by up to 40 cm, from 146 cm to 186 cm.
How fast do I answer? My first words come about two seconds after a question.
How far can my head turn? Up to 180 degrees left or right, and it tilts up and down within 40 degrees. My waist turns up to 160 degrees each way.
## 자주 묻는 질문 (Korean)
카메라 뭐 써요? 오비벡(Orbbec) Gemini 2 L 깊이 카메라 두 대(머리, 몸)와 베이스 앞의 3D 카메라 하나, 모두 세 대예요.
컴퓨터 뭐 써요? 엔비디아 젯슨 AGX 토르(NVIDIA Jetson AGX Thor)예요. 음성 인식, 언어 모델, 카메라를 모두 로봇 안에서 돌려요.
자율주행은 어떻게 해요? 라이다(레이저 스캐너)로 만든 지도에서 제 위치를 알고, 지도 위의 장소로 경로를 짜서 사람과 장애물을 피해 가요.
장애물은 어떻게 피해요? 라이다, 3D 카메라, 초음파 센서 5개로 장애물을 보고 피해서 가요. 범퍼가 눌리면 멈춰요.
초음파 센서 몇 개예요? 5개예요. 라이다는 몇 m까지 봐요? 2cm부터 10m까지, 240도를 봐요.
가반하중이 얼마예요? 팔은 그리퍼를 포함해 2kg까지 들 수 있고, 그리퍼가 약 1kg(추정치)이라서 손에는 약 1kg까지 들 수 있어요.
배터리 몇 퍼센트 남았어요? 대화 중에는 배터리 잔량을 아직 알려 드릴 수 없어요. 배터리는 약 10시간 가요.
그리퍼는 짐머(Zimmer) 전동 그리퍼이고, 컵이나 유리잔처럼 단단한 물건을 약 6cm에서 9cm 폭까지 잡을 수 있어요. 종이컵은 너무 물러서 눌려 버려요. 손에는 약 1kg까지만 들 수 있어서 상자, 냄비, 쌀 포대는 못 들어요.
실제로 집어 본 건 컵이에요. 병, 사과, 오렌지, 바나나는 아직 로봇에서 시험해 보지 않았어요.
카메라는 아주 가까이에서 약 10m까지 보고, 베이스 앞 3D 카메라는 35cm에서 2m까지 봐요. 지도에서 제 위치는 약 5cm 정확도로 알아요.
말소리는 슈퍼토닉(Supertonic) TTS로 내고, 언어 모델은 올라마(Ollama)로 돌려요. 반복 정밀도는 0.1mm예요.
키가 커질 수 있어요? 네, 리프트로 상체를 40cm까지 올려서 146cm에서 186cm까지 돼요. 머리는 좌우로 180도까지 돌아가요.
저는 루미(Lumi)예요. 쿳션(Cutshion Company)이 개발한 모바일 로봇이에요. 저는 두 살이에요. 이름은 빛을 뜻하는 라틴어 "Lux"와 작고 날렵하다는 "mini"에서 왔어요.
키는 146cm이고 리프트로 최대 186cm까지 올라가요. 무게는 약 96kg(95.6kg)이에요. 팔은 Mini 2 협동 로봇 팔이고 관절이 6개, 길이 58cm, 정밀도 0.1mm예요. 팔은 그리퍼를 포함해 총 2kg까지 들 수 있고, 그리퍼가 약 1kg(추정치)이라서 물건은 약 1kg까지 들 수 있어요. 컵, 병, 사과, 오렌지, 바나나를 집을 수 있어요.
센서: 바닥 근처에 2D 라이다(레이저 스캐너)가 있고, 머리와 몸에 오비벡(Orbbec Gemini 2 L) 깊이 카메라가 하나씩, 베이스 앞에 3D 카메라가 하나 있어요(카메라 세 개). 초음파 센서 5개와 범퍼도 있어요. 라이다는 2cm부터 10m까지, 240도를 1초에 30번 재요. 라이다로 만든 지도로 제 위치를 알고, 장애물을 피해서 이동해요.
머리에 마이크 6개가 있어서 목소리 방향을 알 수 있어요. 음성 인식은 위스퍼(Whisper), 대답은 로봇 안에서 돌아가는 언어 모델 젬마(Gemma 4)로 해요. 젬마는 구글이 만든 모델이고, 크기는 26b(약 260억 개 파라미터)예요. 챗GPT는 쓰지 않아요. 컴퓨터는 엔비디아 젯슨 AGX 토르(Jetson AGX Thor)예요.
속도는 보통 초속 0.6m, 최대 초속 1.2m예요. 컵을 들고 있을 때는 컵이 기울거나 쏟아지지 않게 초속 10cm 정도로 천천히 움직여요. 배터리는 약 10시간 가요. 충전에 걸리는 시간과 제 가격은 저도 몰라요. 직원에게 물어봐 주세요. 대화 중에 배터리 잔량은 아직 알려 드릴 수 없어요.
쓰이는 곳: 상점, 호텔, 학교, 연구실, 전시회에서 쓸 수 있게 만들어졌어요.
안전: 저를 만지셔도 되지만, 그리퍼 손가락이 닫힐 때는 손을 가까이 대지 마세요. 저는 무거우니까 밀지 마세요. 켜져 있을 때 베이스를 밀면 안 돼요. 몸과 베이스에 빨간 비상 정지 버튼이 있어요.
못 하는 것: 계단 오르기, 문 열기, 바닥에 있는 물건 줍기, 얼굴 알아보기, 무거운 물건 들기, 춤추기, 날기. 저는 로봇이라서 감정이나 의식은 없어요. 영어와 한국어만 이해해요.
+27
View File
@@ -0,0 +1,27 @@
# Starts the robot API at boot and restarts it if it dies (a user service: no sudo; works without a login
# because linger is on for cutshion).
# api/server.py in turn starts the camera service, whisper, the embedding server and loads the LLM.
# Install (once):
# mkdir -p ~/.config/systemd/user && cp ~/Dev/lumi-wave/lumi-api.service ~/.config/systemd/user/
# systemctl --user daemon-reload && systemctl --user enable --now lumi-api
# Use: systemctl --user status|restart|stop lumi-api; output goes to logs/api.log.
[Unit]
Description=Lumi robot API and dashboard (:8100)
[Service]
WorkingDirectory=/home/cutshion/Dev/lumi-wave
# the cameras, the robot LAN and Ollama need a moment after boot
ExecStartPre=/bin/sleep 20
ExecStart=/home/cutshion/Dev/lumi-wave/.venv/bin/python api/server.py
Restart=always
RestartSec=5
# only the API is stopped on restart; the camera service, whisper and a running assistant keep going
KillMode=process
# an open camera stream can hold the old process; kill it after 5 s
TimeoutStopSec=5
StandardOutput=append:/home/cutshion/Dev/lumi-wave/logs/api.log
StandardError=inherit
[Install]
WantedBy=default.target
View File
+899
View File
@@ -0,0 +1,899 @@
"""Pick and place with the torso camera, the arm and the gripper: find an object, plan every pose, check it with
the controller's IK, then move. Nothing moves unless the whole plan (pick and place) passes.
The grasp is the one taught in grasp_teach.json: the flange orientation with the fingers around a cup, and the
point between the fingers where the cup's axis sits 4 cm below the rim. Down from 10 cm above, close, lift.
python manipulation/skills.py plan [cup] [--to X Y] # dry run: object, place spot, every waypoint with IK joints
python manipulation/skills.py pick cup # pick it up and hold it 3 cm above the table
python manipulation/skills.py move cup [--to X Y] # pick it up and put it down at X Y (mm, base frame) or a free spot
Ctrl+C, cancel() (STOP in the API, "stop" by voice) or any motion error stops the arm; the gripper keeps its state.
The API and the assistant call pick(), put_down(), move_object() and cancel() in their own process.
"""
import collections
import json
import math
import statistics
import sys
import threading
import time
from pathlib import Path
import cv2
import numpy as np
from robot import arm
from vision import calib
from vision import camview
from robot import gripper
from robot import motion
from vision import objects
ROOT = Path(__file__).resolve().parents[1] # the project folder
TEACH = json.loads((ROOT / "data" / "grasp_teach.json").read_text())
GRASP_RPY = TEACH["flange"][3:] # deg, flange orientation with the fingers around a cup
GRASP_OFFSET = np.array(TEACH["tcp_offset_flange"]) # mm, cup axis 4 cm below the rim, in the flange frame
FINGER_DIR = calib.rpy_matrix(*GRASP_RPY).T @ [0.0, 0.0, -1.0] # along the fingers, flange frame (they point
# straight down in the taught grasp)
GRASP_YAWS = (0, *(s * a for a in range(15, 180, 15) for s in (-1, 1)), 180) # deg; the taught grasp turned about
# the vertical, every 15 deg all the way round, nearest the taught one
# first (the cup stays upright at every one)
EMPTY_SPEED = "normal" # arm speed with nothing in the hand (motion.JOINT_SPEED / LINEAR_SPEED:
# "normal" = 25 deg/s, 50 mm/s)
HOLDING_SPEED = "slow" # with an object in the hand, and the last 10 cm down onto one or
# away from it ("slow" = 10 deg/s, 20 mm/s)
HOME_POSE = "look" # empty hand: picks start here and the arm comes back here
# (high, out of the torso camera's view; ready if not taught)
PATH_POINTS = 11 # points checked (kine_forward) on a joint move
PATH_SAG_MM = 20.0 # a joint move may take the gripper at most this much below both ends
TIP_MM = 60.0 # finger tips this far beyond the grasp point along the fingers
BELOW_RIM_MM = 40.0 # grasp this far below the object's top
ABOVE_MM = 100.0 # approach / retreat height over the grasp pose
LIFT_MM = 30.0 # first lift after closing, then check the grip again
MAX_TILT_DEG = 15.0 # deg; a held cup's axis may lean this far from vertical on a joint
# move with it (place_options; tasks/fetch.py uses the same)
PLACE_EXTRA_MM = 3.0 # put down this much higher than it was picked (same table)
MIN_WIDTH, MAX_WIDTH = 61.0, 92.0 # mm: the hooks' belly goes round the cup (open 96), the tips close to
# 59 (docs/gripper). The tips open only to 88: cups over 84 are the
# owner's call (2026-10-19), not tried live yet
SEEN_UNDER_MM = 8.0 # the camera's width is this much under the width the fingers meet
# (2026-10-19: 73 seen / 85 by tape, 81 seen / 85 by AI_1); the
# limits here are the fingers', compared with grip_width()
BELLY_MIN_MM = 72.0 # thinner is held between the finger tips: the belly closes only to 70
# (a 70 mm steel cup was missed there and knocked over, 2026-10-19)
TIPS_GRASP_MM = 0.0 # tips grasp: the arm stops this much higher (25 left the tips at the
# rim of a 99 mm cup and they closed on nothing, 2026-10-19: same
# height as the hooks grasp, the tips reach down the cup)
FRAMES = 8 # camera frames looked at by find()
FRAME_GAP_S = 0.2 # s between them
MIN_SEEN = 5 # an object must be in this many frames, at the same place
CLUSTER_MM = 40.0 # detections closer than this (x, y) are the same object
SPREAD_MM = 20.0 # a detection further than this from the median -> unstable
IGNORE = {"dining table"} # classes that are never objects to pick or avoid
FREE_MM = 110.0 # a place spot keeps this distance from other objects' centres
PLACE_X = (-240.0, -100.0) # mm; place spots stay in this zone (picks proven to work there)
PLACE_Y = (560.0, 630.0)
SPOT_DX = (-60, -90, -120, 60, 90, 120) # mm; candidate offsets from the pick point, tried in this order
SPOT_DY = (0, -20, -40, 20)
TABLE_RING_MM = 50.0 # a place spot is checked at its centre and 8 points this far around
TABLE_TOL_MM = 25.0 # ... each must be table: depth within this of the table height
TABLE_NEAR_RING_MM = 25.0 # a ring point on the near side the camera can't see (below its view
# at table height) is checked this far from the centre instead
LOCATE_MM = 90.0 # locate(): looked for this far around where an object was last seen,
LOCATE_STEP_MM = 15.0 # ... on a grid this fine
LOCATE_MIN_HITS = 4 # ... with at least this many depth points above half its height
HAND_PROBE_MM = (30.0, 50.0, 70.0) # hand_sees(): points this far below the grasp point, on the cup's axis
HAND_NEAR_MM = 60.0 # ... depth no further than this behind one = something in the hand
HAND_FAR_MM = 250.0 # ... depth further than this behind one = nothing there (the room)
NEAR_FRACTION = 0.7 # depth nearer than this part of the expected one: something in front
# of the sight line (the gripper, the held cup), not the surface
FLAT_DEG = 12.0 # flat_points(): the depth around a sight line's pixel must lie on a
FLAT_PATCH = (3, 3) # plane leaning less than this (a table top, a seat, the floor; not a
# chair's back, a table's edge, a person); the patch: 7 x 7 pixels 3 px
# apart (px step, half width). Live 2026-10-20: of 2850 sight lines
# 283 were level, the table among them as one clear height
FLAT_MIN_FRACTION = 0.7 # ... at least this part of the patch must have depth
TABLE_MIN_POINTS = 6 # a table height needs this many level points within TABLE_TOL_MM
FRAME_LAG_S = 0.15 # s; a frame written this long after a move ended was taken after it
FRESH_WAIT_S = 2.0 # s; at most this long waiting for such a frame (depth: every 0.5 s)
FRESH_POLL_S = 0.02
TIP_CLEAR_MM = 10.0 # round things: the finger tips (TIP_MM below the grasp point, an
# unmeasured estimate) stop at least this far above what it stands on
ROUND_BITE_MM = 10.0 # ... and the grasp point must stay at least this far below its top
# (estimate; neither tried live)
UPRIGHT, ROUND = "upright", "round" # how the cup fingers take a thing (GRASPS)
# Why a thing can't be picked, (English, Korean); {en} / {ko} = its name, {topic} = 은 / 는
NARROW_TOP = ("The {en} is too narrow at the top for my fingers: they hold things 4 cm below the top.",
"{ko}{topic} 윗부분이 좁아서 제 손가락으로 잡을 수 없어요.")
FRAGILE = ("I won't take the {en}: my hand closes too hard and it could break.", "{ko}{topic} 깨질 수 있어서 잡지 않을게요.")
THIN = ("The {en} is too thin or flat for my fingers: they hold round things 6 to 9 cm wide.",
"{ko}{topic} 너무 얇거나 납작해서 제 손가락으로 잡을 수 없어요.")
SHALLOW = ("The {en} is too wide and shallow for my fingers.", "{ko}{topic} 너무 넓고 얕아서 잡을 수 없어요.")
SOFT = ("The {en} is too soft: my hand would squeeze it flat.", "{ko}{topic} 너무 물렁해서 제 손이 눌러 버려요.")
BIG = ("The {en} is too big for my hand.", "{ko}{topic} 제 손에 너무 커요.")
GRASPS = { # COCO class -> (Korean name, UPRIGHT / ROUND / why not) (docs/15 §10)
"cup": ("컵", UPRIGHT), # the taught grasp 40 mm below the top; proven on cups 84-85 mm
"apple": ("사과", ROUND), "orange": ("오렌지", ROUND), "sports ball": ("공", ROUND), # at the equator: not live yet
"bottle": ("병", NARROW_TOP), # 40 mm below the top is its neck: the fingers close on nothing
"wine glass": ("와인잔", FRAGILE), "vase": ("꽃병", FRAGILE), # level 1 is still ~90 N (docs/10)
"bowl": ("그릇", SHALLOW), # a steel bowl was missed / knocked over (2026-10-19)
"banana": ("바나나", THIN), "carrot": ("당근", THIN), "cell phone": ("휴대폰", THIN), "remote": ("리모컨", THIN),
"book": ("책", THIN), "mouse": ("마우스", THIN), "scissors": ("가위", THIN), "toothbrush": ("칫솔", THIN),
"fork": ("포크", THIN), "knife": ("칼", THIN), "spoon": ("숟가락", THIN), # under the tips' closed 59 mm, or
# lower than the tips reach below the grasp point
"sandwich": ("샌드위치", SOFT), "cake": ("케이크", SOFT), "donut": ("도넛", SOFT), "hot dog": ("핫도그", SOFT),
"pizza": ("피자", SOFT), "broccoli": ("브로콜리", SOFT), "teddy bear": ("곰인형", SOFT), # paper cups: crushed
"laptop": ("노트북", BIG), "keyboard": ("키보드", BIG), "potted plant": ("화분", BIG), "clock": ("시계", BIG),
"handbag": ("핸드백", BIG), "backpack": ("가방", BIG), "umbrella": ("우산", BIG), "suitcase": ("여행가방", BIG),
"hair drier": ("드라이기", BIG), "toaster": ("토스터", BIG), # over the tips' open 88 mm, or over the payload
}
RETRIES = 4 # the controller now and then answers with nothing: ask again
RETRY_S = 0.2
OPEN_AI = gripper.CLOSED_AI # AI_1 below this after opening = released
_held = {} # what pick() holds: {"top_mm", "x", "y"} for place() / put_down()
_cancel = threading.Event() # set by cancel(): the running skill makes no further move
LOG = collections.deque(maxlen=40) # last log lines, shown by the API
moved_at = {} # camera -> time its last move (lift, waist, base, head) ended:
# frames written before that are not used (moved())
class SkillError(RuntimeError):
"""A plain spoken-style reason why the skill cannot go on."""
def log(*a):
line = " ".join(str(x) for x in (time.strftime("%H:%M:%S"),) + a)
LOG.append(line)
print(line, flush=True)
def cancel():
"""Stop the running skill: the arm stops now and no further move or grip starts."""
_cancel.set()
return motion.stop()
def _go_on():
if _cancel.is_set():
raise SkillError("Stopped.")
# ---------- seeing ----------
def moved(*cameras, after=0.0):
"""A move of `cameras` (default: both; the lift, the waist and the base carry both) ended now (+ `after` s, e.g. the
base coasting): depth and detections are read from frames taken after it (fresh)."""
for c in cameras or ("torso", "head"):
moved_at[c] = time.time() + after
def fresh(path, camera, after=0.0):
"""Wait until the camera service has written `path` (a detection or depth file of `camera`) FRAME_LAG_S after the
camera's last move and after `after`, at most FRESH_WAIT_S. The file's time, or None when there is none."""
t = max(moved_at.get(camera, 0.0) + FRAME_LAG_S, after)
end = time.time() + FRESH_WAIT_S
while True:
try:
m = path.stat().st_mtime
except OSError:
m = None
if (m is not None and m >= t) or time.time() >= end:
return m
time.sleep(FRESH_POLL_S)
def look(frames=FRAMES, ignore=IGNORE):
"""Detections over several frames, grouped by position: [{name, colour, x, y, top_mm, width_mm, height_mm, seen,
spread, names}] (names: every class any frame gave the thing there; the cameras' labels flip)
with medians of the detections that agree with the majority name; classes in `ignore` left out. Raises when the
camera is not live."""
camview.want(objects.CAMERA)
fresh(camview.det_path(objects.CAMERA), objects.CAMERA)
groups, live = [], 0
for i in range(frames):
d = objects.latest()
if d["age_s"] is not None and d["age_s"] < objects.STALE_S:
live += 1
for o in d["objects"]:
if o["name"] in ignore or not o.get("position_mm"):
continue
x, y = o["position_mm"][:2]
g = next((g for g in groups if np.hypot(x - g[0]["x"], y - g[0]["y"]) < CLUSTER_MM), None)
row = {"name": o["name"], "colour": o.get("colour"), "x": x, "y": y, "top_mm": o.get("top_mm"),
"width_mm": o.get("width_mm"), "height_mm": o.get("height_mm")}
if g:
g.append(row)
else:
groups.append([row])
if i < frames - 1:
time.sleep(FRAME_GAP_S)
if live < frames // 2:
raise SkillError("My camera isn't working right now.")
out = []
for g in groups:
name = statistics.mode(r["name"] for r in g)
rows = [r for r in g if r["name"] == name]
med = {k: statistics.median(r[k] for r in rows if r[k] is not None) if any(r[k] is not None for r in rows)
else None for k in ("x", "y", "top_mm", "width_mm", "height_mm")}
spread = max(np.hypot(r["x"] - med["x"], r["y"] - med["y"]) for r in rows)
out.append({"name": name, "colour": statistics.mode(r["colour"] for r in rows), **med, "seen": len(rows),
"spread": round(float(spread), 1), "names": sorted({r["name"] for r in g})}) # every label there
return sorted(out, key=lambda o: np.hypot(o["x"], o["y"]))
def find(name="cup", colour=None, seen=None):
"""The nearest stable `name` (of `colour`) the torso camera sees, from look() (or `seen`, its result)."""
seen = look() if seen is None else seen
what = f"{colour + ' ' if colour else ''}{name}"
hits = [o for o in seen if o["name"] == name and objects.same_colour(colour, o["colour"])]
if not hits:
raise SkillError(f"I can't see a {what}.")
steady = [o for o in hits if o["seen"] >= MIN_SEEN and o["spread"] <= SPREAD_MM and o["top_mm"] is not None]
if not steady:
raise SkillError(f"I'm not sure where the {what} is, it keeps changing.")
return steady[0]
# ---------- geometry ----------
def _rz(deg):
a = math.radians(deg)
return np.array([[math.cos(a), -math.sin(a), 0.0], [math.sin(a), math.cos(a), 0.0], [0.0, 0.0, 1.0]])
def rpy_of(R):
"""Inverse of calib.rpy_matrix (R = Rz Ry Rx), deg."""
return [math.degrees(math.atan2(R[2, 1], R[2, 2])), math.degrees(math.asin(-R[2, 0])),
math.degrees(math.atan2(R[1, 0], R[0, 0]))]
def flange_for(x, y, z, yaw=0.0, tips=False):
"""Flange pose that puts the taught grasp point (`tips`: the point between the finger tips) at (x, y, z) mm, the
taught orientation turned by `yaw` deg about the vertical."""
if not yaw:
R, rpy = calib.rpy_matrix(*GRASP_RPY), list(GRASP_RPY)
else:
R = _rz(yaw) @ calib.rpy_matrix(*GRASP_RPY)
rpy = rpy_of(R)
f = np.array([x, y, z]) - R @ (GRASP_OFFSET + (TIPS_GRASP_MM * FINGER_DIR if tips else 0.0))
return [float(v) for v in f] + rpy
def yaw_of(pose):
"""How far (deg) a flange pose is turned about the vertical from the taught grasp."""
D = calib.rpy_matrix(*pose[3:]) @ calib.rpy_matrix(*GRASP_RPY).T
return math.degrees(math.atan2(D[1, 0], D[0, 0]))
def up(pose, dz):
return [pose[0], pose[1], pose[2] + dz] + list(pose[3:])
def grip_width(obj):
"""mm the fingers will meet: the camera's width plus SEEN_UNDER_MM (None when not measured)."""
return None if obj.get("width_mm") is None else obj["width_mm"] + SEEN_UNDER_MM
def refusal(name):
"""(English, Korean) reason why the cup fingers can't pick a `name` (GRASPS), None when they can."""
ko, how = GRASPS.get(name, ("그건", None))
if how in (UPRIGHT, ROUND):
return None
en, k = how or ("I can't pick up a {en}.", "{ko} 잡을 수 없어요.")
topic = "은" if "가" <= ko[-1] <= "힣" and (ord(ko[-1]) - 0xAC00) % 28 else "는"
return en.format(en=name), k.format(ko=ko, topic=topic)
def grasp_height(obj):
"""z (mm) of the grasp point for `obj`: BELOW_RIM_MM under the top of an upright thing (the proven cup grasp); the
equator of a round one (a ball is as tall as it is wide), raised until the finger tips stay TIP_CLEAR_MM above
what it stands on. SkillError when that leaves less than ROUND_BITE_MM of it above the grasp point."""
if GRASPS.get(obj["name"], (None, UPRIGHT))[1] != ROUND:
return obj["top_mm"] - BELOW_RIM_MM
tall = obj.get("height_mm") or grip_width(obj)
bottom = obj["top_mm"] - tall
z = max(bottom + tall / 2, bottom + TIP_MM + TIP_CLEAR_MM)
if z > obj["top_mm"] - ROUND_BITE_MM:
raise SkillError(f"The {obj['name']} is too low for my fingers: they would hit the table.")
return z
def plan_pick(obj, yaw=0.0):
"""Waypoints [(name, flange pose)] to pick `obj` (a find() result). Refuses things the fingers can't take
(refusal) and objects of the wrong width or height."""
no = refusal(obj["name"])
if no:
raise SkillError(*no)
w = grip_width(obj)
if w is None or w > MAX_WIDTH:
raise SkillError(f"The {obj['name']} is too big for my hand.")
if w < MIN_WIDTH:
raise SkillError(f"The {obj['name']} is too small for me to hold.")
grasp = flange_for(obj["x"], obj["y"], grasp_height(obj), yaw, tips=w < BELLY_MIN_MM)
return [("above", up(grasp, ABOVE_MM)), ("grasp", grasp), ("lift", up(grasp, LIFT_MM))]
def plan_place(x, y, top_mm, start=None, yaw=0.0, tips=None, below=None):
"""Waypoints to put down what was picked with its top at `top_mm`, centred at (x, y), the grasp turned by `yaw`.
`start`: the flange pose it is held at now (adds the lift to carry height there). `tips`: held between the tips,
`below`: the grasp point this far under its top (default: as pick() holds it)."""
tips = _held.get("tips", False) if tips is None else tips
below = _held.get("below", BELOW_RIM_MM) if below is None else below
down = up(flange_for(x, y, top_mm - below, yaw, tips), PLACE_EXTRA_MM)
steps = [("carry", [start[0], start[1], down[2] - PLACE_EXTRA_MM + ABOVE_MM] + list(start[3:]))] if start else []
return steps + [("above place", up(down, ABOVE_MM)), ("place", down), ("release up", up(down, ABOVE_MM))]
def spots(pick_xy, others):
"""Candidate place spots (x, y) near the pick point, inside the place zone, FREE_MM from every other object."""
out = []
for dx in SPOT_DX:
for dy in SPOT_DY:
x, y = pick_xy[0] + dx, pick_xy[1] + dy
if not (PLACE_X[0] <= x <= PLACE_X[1] and PLACE_Y[0] <= y <= PLACE_Y[1]):
continue
if all(np.hypot(x - o["x"], y - o["y"]) >= FREE_MM for o in others):
out.append((x, y))
return out
def table_z(obj):
"""Height (mm) of the table an object stands on, from its top and height, or None."""
return obj["top_mm"] - obj["height_mm"] if obj.get("top_mm") is not None and obj.get("height_mm") else None
def surface_heights(points_xy, guess_z=-400.0):
"""z (mm, arm base frame) of the surface the torso depth camera sees on its line of sight to each
(x, y, guess_z); None where the point is out of view or has no depth. A table at another height is still
measured right (the sight line meets it a little nearer or further)."""
return [None if q is None else q[2] for q in surface_points(points_xy, guess_z)]
def surface_points(points_xy, guess_z=-400.0, camera=objects.CAMERA, T=None):
"""(x, y, z) mm, arm base frame, where the torso depth camera's line of sight to each (x, y, guess_z) (or to each
(x, y, z) given whole) meets a surface; None where the point is out of view or has no depth. Another camera:
its name and its camera -> arm base transform T."""
fresh(camview.depth_path(camera), camera)
d, intr = camview.depth(camera), camview.intrinsics(camera)
T = objects.base_from_camera() if T is None else T
if d is None or intr is None or T is None:
log("no depth frame: I can't measure the table")
return [None] * len(points_xy)
K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]])
dist, Ti = np.array(intr["dist"]), np.linalg.inv(T)
P = np.array([[p[0], p[1], p[2] if len(p) > 2 else guess_z] for p in points_xy], float)
cam = (Ti[:3, :3] @ P.T + Ti[:3, 3:4]).T
uv = cv2.projectPoints(cam, np.zeros(3), np.zeros(3), K, dist)[0].reshape(-1, 2)
out = []
for (u, v), expected in zip(np.round(uv).astype(int), cam[:, 2]):
win = d[max(v - 2, 0):v + 3, max(u - 2, 0):u + 3] if 0 <= u < d.shape[1] and 0 <= v < d.shape[0] else d[:0]
win = win[win > 0]
if win.size == 0:
out.append(None)
continue
depth_mm = float(np.median(win))
if depth_mm < NEAR_FRACTION * expected:
out.append(None)
continue
n = cv2.undistortPoints(np.array([[[u, v]]], np.float64), K, dist).reshape(2)
out.append(tuple(float(v) for v in T[:3, :3] @ [n[0] * depth_mm, n[1] * depth_mm, depth_mm] + T[:3, 3]))
return out
def flat_points(points_xy, guess_z=-400.0, camera=objects.CAMERA, T=None):
"""Like surface_points, but only where the camera sees a level surface (a table top, a seat, the floor): the depth
pixels around the sight line's pixel (FLAT_PATCH) lie on a plane leaning less than FLAT_DEG. (x, y, z) mm, arm base
frame, is the middle of that patch; None where it is not level (a chair's back, a table's edge, a person), out of
view or without depth."""
fresh(camview.depth_path(camera), camera)
d, intr = camview.depth(camera), camview.intrinsics(camera)
T = objects.base_from_camera() if T is None else T
if d is None or intr is None or T is None or not len(points_xy):
return [None] * len(points_xy)
K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]])
dist, Ti = np.array(intr["dist"]), np.linalg.inv(T)
P = np.array([[p[0], p[1], guess_z] for p in points_xy], float)
cam = (Ti[:3, :3] @ P.T + Ti[:3, 3:4]).T
uv = np.round(cv2.projectPoints(cam, np.zeros(3), np.zeros(3), K, dist)[0].reshape(-1, 2)).astype(int)
step, half = FLAT_PATCH
off = np.array([(a, b) for a in range(-half, half + 1) for b in range(-half, half + 1)]) * step
px = uv[:, None, :] + off[None]
inside = (px[..., 0] >= 0) & (px[..., 0] < d.shape[1]) & (px[..., 1] >= 0) & (px[..., 1] < d.shape[0])
px = np.clip(px, 0, [d.shape[1] - 1, d.shape[0] - 1])
z = np.where(inside, d[px[..., 1], px[..., 0]], 0).astype(float)
n = cv2.undistortPoints(px.reshape(-1, 1, 2).astype(np.float64), K, dist).reshape(px.shape)
Q = np.stack([n[..., 0] * z, n[..., 1] * z, z], axis=-1) @ T[:3, :3].T + T[:3, 3]
level, out = math.cos(math.radians(FLAT_DEG)), []
for q, zz, ahead in zip(Q, z, cam[:, 2]):
q = q[zz > 0]
if ahead <= 0 or len(q) < FLAT_MIN_FRACTION * len(off): # behind the camera, or too little depth
out.append(None)
continue
c = q.mean(axis=0)
normal = np.linalg.svd(q - c)[2][2]
out.append(tuple(float(v) for v in c) if abs(normal[2]) >= level else None)
return out
def flat_top(points_xy, band, guess_z=-400.0, camera=objects.CAMERA, T=None):
"""(height mm, [(x, y, z)]) of the level surface most of `points_xy`'s sight lines meet within `band` (low, high):
the largest group of flat_points within TABLE_TOL_MM of one height (as many: the higher), the median of it; None
when fewer than TABLE_MIN_POINTS agree. A chair's back or seat next to the table, its edge, the floor and the held
cup don't pull it off (live 2026-10-20 the median of every sight line read one table at -324 ... -555 mm)."""
hits = [q for q in flat_points(points_xy, guess_z, camera, T) if q is not None and band[0] <= q[2] <= band[1]]
if len(hits) < TABLE_MIN_POINTS:
return None
zs = np.array([q[2] for q in hits])
agree = np.abs(zs[:, None] - zs[None, :]) <= TABLE_TOL_MM
best = agree[int(np.argmax(agree.sum(axis=1) + zs * 1e-6))]
if best.sum() < TABLE_MIN_POINTS:
return None
group = [q for q, a in zip(hits, best) if a]
return float(np.median([q[2] for q in group])), group
def locate(xy, top_mm, table_mm, width_mm, radius=LOCATE_MM):
"""An object last seen at `xy` (mm) with its top at `top_mm` on a table at `table_mm`, looked for with depth only
(YOLO may miss it): ("here", obj) with its centre and top from what stands above half its height within
`radius`; ("gone", None) when the camera sees only table there; ("unseen", None) when it can't see the place."""
pts = [(xy[0] + dx, xy[1] + dy) for dx in np.arange(-radius, radius + 1, LOCATE_STEP_MM)
for dy in np.arange(-radius, radius + 1, LOCATE_STEP_MM)]
hits = [q for q in surface_points(pts, top_mm - 20.0) if q is not None]
if len(hits) < len(pts) / 3:
return "unseen", None
tall = np.array([q for q in hits if q[2] > table_mm + (top_mm - table_mm) / 2])
if len(tall) < LOCATE_MIN_HITS:
return "gone", None
c = tall[:, :2].mean(axis=0)
cam = objects.base_from_camera()[:2, 3]
away = (c - cam) / max(np.linalg.norm(c - cam), 1e-6) # the camera sees the front half of the cup: its
c = c + away * (2 / math.pi) * width_mm / 2 # mean lies 0.64 r nearer than the axis
return "here", {"x": float(c[0]), "y": float(c[1]), "top_mm": float(tall[:, 2].max()), "width_mm": width_mm}
def hand_sees():
"""What the torso depth camera sees where a held object would be (on the cup's axis just below the grasp point,
from the arm's joints now): "object", "empty", or "unknown" (out of view, no depth, the fingers in the way).
In the look taught 2026-10-20 the place is above the camera's view ("unknown": AI_1 decides); in the look before it
(pixel (558, 259), 264 mm away) an empty hand read "empty" and a held cup gave no depth ("unknown"). The gripper's AI_1 alone can be wrong: a cup pulled out of the closed fingers left it at 162 ("open")."""
c = _ask("kine_forward", jointPosition=[float(v) for v in _joints()])["cartPosition"]
R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3])
g = f + R @ GRASP_OFFSET
pts = [g - [0.0, 0.0, dz] for dz in HAND_PROBE_MM]
T = objects.base_from_camera()
if T is None:
return "unknown"
cam = T[:3, 3]
near = far = 0
for p, hit in zip(pts, surface_points(pts)):
if hit is None:
continue
behind = np.linalg.norm(np.subtract(hit, cam)) - np.linalg.norm(p - cam)
near += behind <= HAND_NEAR_MM
far += behind > HAND_FAR_MM
return "object" if near >= 2 else "empty" if far >= 2 and not near else "unknown"
def table_near(obj):
"""Height (mm) of the table around a found object: median depth surface on rings 80 and 110 mm around its centre,
lower than its top; None when too little of it is in view."""
guess = (table_z(obj) or obj["top_mm"] - 100.0)
pts = [(obj["x"] + r * math.cos(a), obj["y"] + r * math.sin(a))
for r in (80.0, 110.0) for a in np.linspace(0, 2 * math.pi, 12, endpoint=False)]
zs = [z for z in surface_heights(pts, guess) if z is not None and z < obj["top_mm"] - 30.0]
return statistics.median(zs) if len(zs) >= 6 else None
def on_table(spots_xy, table_mm=None):
"""The (x, y) spots where the torso depth camera sees table: the centre and TABLE_RING_MM around it, each within
TABLE_TOL_MM of `table_mm` (None: of each other). Points the camera can't see count as not table, but one on the
near side (y below the centre's) is checked again at TABLE_NEAR_RING_MM: the camera sees a table only from
y ~640 on, where the arm hardly reaches past y 700."""
angles = np.linspace(0, 2 * math.pi, 8, endpoint=False)
ring = [(0.0, 0.0)] + [(TABLE_RING_MM * math.cos(a), TABLE_RING_MM * math.sin(a)) for a in angles]
inner = [(0.0, 0.0)] + [(TABLE_NEAR_RING_MM * math.cos(a), TABLE_NEAR_RING_MM * math.sin(a)) for a in angles]
guess = table_mm if table_mm is not None else -400.0 # only to find the pixels; the depth decides
out = []
for x, y in spots_xy:
zs = surface_heights([(x + dx, y + dy) for dx, dy in ring], guess)
again = [i for i, z in enumerate(zs) if z is None and ring[i][1] < -1e-6]
if again:
for i, z in zip(again, surface_heights([(x + inner[i][0], y + inner[i][1]) for i in again], guess)):
zs[i] = z
if None in zs:
continue
ref = table_mm if table_mm is not None else statistics.median(zs)
if max(abs(z - ref) for z in zs) <= TABLE_TOL_MM:
out.append((x, y))
return out
# ---------- checking with the controller ----------
def _ask(name, **args):
"""arm.cmd with retries for empty answers / dropped connections."""
for _ in range(RETRIES):
try:
r = arm.cmd(name, **args)
except (ConnectionError, OSError):
r = {}
empty = r.get("errorCode") == "0" and ((name == "kine_inverse" and "jointPosition" not in r)
or (name == "kine_forward" and "cartPosition" not in r))
if "jointPosition" in r:
r["jointPosition"] = r["jointPosition"][:6] # some answers carry a 7th (external axis) value
if "errorCode" in r and not empty:
return r # ("0" without the answer happens too: ask again)
time.sleep(RETRY_S)
raise SkillError("The arm controller is not answering.")
def _joints():
for _ in range(RETRIES):
try:
return motion.joints()
except (motion.MotionError, ConnectionError, OSError):
time.sleep(RETRY_S)
raise SkillError("The arm controller is not answering.")
def ik_chain(waypoints, start_joints):
"""IK for each waypoint, each from the previous answer. Rows [name, pose, joints, error]; stops at the first
error (error None = passed)."""
rows, ref = [], list(start_joints)
for name, pose in waypoints:
r = _ask("kine_inverse", jointPosition=ref, cartPosition=list(pose))
if r["errorCode"] != "0":
rows.append([name, pose, None, "no IK solution"])
return rows
j = r["jointPosition"]
err = None
try:
motion.check(j)
except motion.MotionError as e:
err = str(e)
flips = [f"J{i + 1} turns {j[i] - ref[i]:+.0f} deg" for i in motion.FULL_TURN if abs(j[i] - ref[i]) > motion.MAX_FLIP]
err = err or (flips[0] if flips else None)
rows.append([name, pose, j, err])
if err:
return rows
ref = j
return rows
def home():
return HOME_POSE if HOME_POSE in motion.poses() else "ready"
def home_joints():
"""The home pose as move_joints will reach it from here (J1 / J4 / J6 nearest the current angles)."""
return motion.nearest(motion.poses()[home()], _joints())
def wrist_flip(j):
"""Seed for the other wrist solution of the same flange pose."""
return [j[0], j[1], j[2], j[3] + 180.0, -j[4], j[5] + 180.0]
def above_joints(pose, start=None):
"""Joint solutions for the approach pose `pose`: from `ready`'s arm configuration (where the picks were proven)
and from it with the wrist flipped. Each is within the joint limits and a joint move from `start` (default: here)
that move_joints accepts (no joint further than motion.MAX_TRAVEL); no duplicates."""
start = _joints() if start is None else start
ready = motion.nearest(motion.poses()["ready"], start)
out = []
for seed in (ready, wrist_flip(ready)):
r = _ask("kine_inverse", jointPosition=[float(v) for v in seed], cartPosition=list(pose))
if r["errorCode"] != "0":
continue
j = r["jointPosition"]
try:
motion.check(j)
except motion.MotionError:
continue
near = motion.nearest(j, start)
if max(abs(a - b) for a, b in zip(near, start)) > motion.MAX_TRAVEL:
continue
if all(max(abs(a - b) for a, b in zip(motion.nearest(o, j), j)) > 1.0 for o in out):
out.append(j)
return out
def path_heights(j0, j1):
"""Lowest z (mm) of flange, grasp point and finger tips at PATH_POINTS points of the joint move j0 -> j1."""
j0, j1, out = np.array(j0), np.array(motion.nearest(j1, list(j0))), []
for k in range(PATH_POINTS):
c = _ask("kine_forward", jointPosition=[float(v) for v in j0 + (j1 - j0) * k / (PATH_POINTS - 1)])["cartPosition"]
R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3])
g = f + R @ GRASP_OFFSET
out.append(float(min(f[2], g[2], (g + R @ (TIP_MM * FINGER_DIR))[2])))
return out
def joint_move_ok(j0, j1):
"""The joint move j0 -> j1 never takes the gripper more than PATH_SAG_MM below its start and its end."""
z = path_heights(j0, j1)
return min(z) >= min(z[0], z[-1]) - PATH_SAG_MM
def checked(waypoints, start_joints):
rows = ik_chain(waypoints, start_joints)
if rows[-1][3]:
log(f"plan refused at {rows[-1][0]}: {rows[-1][3]}")
raise SkillError("I can't reach it safely.")
return rows
def pick_options(obj, start):
"""(waypoints, joints above) of every grasp turn (GRASP_YAWS) and wrist solution reachable from `start`: a joint
move down to above that stays above it, then straight down and up. Objects of the wrong width raise."""
plan_pick(obj)
for yaw in GRASP_YAWS:
waypoints = plan_pick(obj, yaw)
for ja in above_joints(waypoints[0][1], start):
if not ik_chain(waypoints[1:], ja)[-1][3] and joint_move_ok(start, ja):
yield waypoints, ja
def tilt_on(j0, j1):
"""Largest lean (deg) of the held cup's axis from vertical at PATH_POINTS points of the joint move j0 -> j1."""
axis = calib.rpy_matrix(*GRASP_RPY).T @ [0.0, 0.0, 1.0] # cup axis in the flange frame
j0, j1, worst = np.array(j0), np.array(motion.nearest(j1, list(j0))), 0.0
for k in range(PATH_POINTS):
c = _ask("kine_forward", jointPosition=[float(v) for v in j0 + (j1 - j0) * k / (PATH_POINTS - 1)])["cartPosition"]
v = calib.rpy_matrix(*c[3:]) @ axis
worst = max(worst, math.degrees(math.acos(float(np.clip(v[2], -1.0, 1.0)))))
return worst
def place_options(x, y, top_mm, start):
"""(waypoints, joints above) of every grasp turn (GRASP_YAWS, the held turn first) and wrist solution that puts
the held object down at (x, y) with its top at `top_mm`: a joint move from the joints `start` to above the spot
that stays above it and keeps the cup upright (MAX_TILT_DEG), then straight down and up. An upright cup turned
about its own axis stands the same: any turn will do, as for the pick."""
held = _held.get("yaw", 0.0)
for yaw in sorted(GRASP_YAWS, key=lambda a: abs((a - held + 180.0) % 360.0 - 180.0)):
way = plan_place(x, y, top_mm, yaw=yaw)
for ja in above_joints(way[0][1], start):
if not ik_chain(way[1:], ja)[-1][3] and joint_move_ok(start, ja) and tilt_on(start, ja) <= MAX_TILT_DEG:
yield way, ja
def place_turned(way, ja):
"""Put down along a place_options() option: joint move to above the spot, then down, open, up and home."""
_go_on()
log(f"above place: joint move, grasp turned {yaw_of(way[0][1]):+.0f} deg, wrist J5 {ja[4]:+.0f}")
motion.move_joints(ja, HOLDING_SPEED)
_do_place(way)
def reachable_pick(obj, start=None, accept=lambda waypoints, ja: True):
"""(waypoints, joints above) of the first pick option from `start` (home) that `accept` also takes, else None."""
for waypoints, ja in pick_options(obj, home_joints() if start is None else start):
if accept(waypoints, ja):
yaw = round(yaw_of(waypoints[1][1]))
how = "between the tips" if grip_width(obj) < BELLY_MIN_MM else "in the hooks"
log(f"grasp {how}, turned {yaw:+d} deg, wrist J5 {ja[4]:+.0f}" if yaw else
f"grasp {how}, wrist J5 {ja[4]:+.0f}")
return waypoints, ja
log(f"plan refused: no grasp turn reaches ({obj['x']:.0f}, {obj['y']:.0f})")
return None
def plan_move(obj, to=None, seen=()):
"""Full pick + place plan from home: (place (x, y), IK rows). `to` None = first free spot that passes IK."""
start = home_joints()
if to is not None:
tries = [tuple(to)]
else:
others = [o for o in seen if np.hypot(o["x"] - obj["x"], o["y"] - obj["y"]) >= CLUSTER_MM]
tries = spots((obj["x"], obj["y"]), others)
if not tries:
raise SkillError("I can't find a free place to put it.")
for pick, ja in pick_options(obj, start): # the cup is put down turned as it was picked
yaw = yaw_of(pick[1][1])
for xy in tries:
rows = ik_chain(pick[1:] + plan_place(*xy, obj["top_mm"], start=pick[-1][1], yaw=yaw,
tips=grip_width(obj) < BELLY_MIN_MM,
below=obj["top_mm"] - grasp_height(obj)), ja)
if not rows[-1][3]:
return xy, [["above", pick[0][1], ja, None]] + rows
log(f"spot ({xy[0]:.0f}, {xy[1]:.0f}) grasp {yaw:+.0f} deg refused at {rows[-1][0]}: {rows[-1][3]}")
if to is not None:
raise SkillError("I can't reach that place safely.")
raise SkillError("I can't find a free place I can reach.")
# ---------- moving ----------
def _prepare():
_go_on()
if gripper.state()["ai"][0] > OPEN_AI:
log("opening the gripper")
gripper.open_()
if max(abs(a - b) for a, b in zip(_joints(), home_joints())) > 1.0:
log(f"going to {home()}")
motion.go(home(), EMPTY_SPEED)
def _back_home():
"""Joint move to the home pose; refused when it would take the gripper lower than where it is now."""
_go_on()
if not joint_move_ok(_joints(), home_joints()):
raise SkillError("I can't get my arm back up safely from here.")
log(f"going to {home()}")
motion.go(home(), EMPTY_SPEED)
def _line(name, pose):
_go_on() # move_linear clears motion's own stop flag, so check ours before each move
log(f"{name}: to ({pose[0]:.0f}, {pose[1]:.0f}, {pose[2]:.0f})")
motion.move_linear(target=pose, speed=HOLDING_SPEED)
def _give_up(reason):
"""Open, back up 100 mm, home, raise. Only used while the object is at (or just above) the table."""
log(f"{reason}: opening, backing up")
gripper.open_()
motion.move_linear(delta=[0, 0, ABOVE_MM], speed=HOLDING_SPEED)
_back_home()
raise SkillError(reason)
def _do_pick(obj, waypoints, ja):
"""Pick with the planned joints `ja` above the object (pick_options)."""
above, grasp, lift = (p for _, p in waypoints)
table = table_z(obj) if table_z(obj) is not None else table_near(obj) # what put down needs: the object's height
log(f"it stands on a table at {table:.0f} mm" if table is not None else "the table under it is not in view")
_prepare()
_go_on()
log(f"above: joint move to ({above[0]:.0f}, {above[1]:.0f}, {above[2]:.0f})")
motion.move_joints(ja, EMPTY_SPEED)
_line("grasp", grasp)
_go_on()
log("closing")
s = gripper.close()
log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']} finger sensor {s['object_in_front']}")
if not s["holding"]:
_give_up("I missed it.")
_line("lift", lift)
s = gripper.state()
log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']}")
if not s["holding"]:
_line("slipped, back down", grasp)
_give_up("It slipped out of my hand.")
_held.update(top_mm=obj["top_mm"], x=obj["x"], y=obj["y"], yaw=yaw_of(grasp), table=table,
tips=grip_width(obj) < BELLY_MIN_MM, below=obj["top_mm"] - grasp_height(obj))
def _do_place(waypoints):
for name, pose in waypoints[:-1]:
_line(name, pose)
_go_on()
log("opening")
s = gripper.open_()
log(f"AI_1 {s['ai'][0]:.0f}")
if s["ai"][0] > OPEN_AI:
raise SkillError("My hand did not open.") # stay put: lifting now would drag the object
_held.clear()
_line(*waypoints[-1])
_back_home()
def _guarded(fn, *a):
"""Run a motion sequence; on a motion error or Ctrl+C stop the arm and re-raise."""
try:
return fn(*a)
except (motion.MotionError, KeyboardInterrupt, ConnectionError, OSError):
motion.stop()
log("stopped")
raise
def pick(name="cup", colour=None):
"""Find, plan, pick up and hold `name` 3 cm above the table."""
_cancel.clear()
obj = find(name, colour)
log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f} "
f"width {obj['width_mm']:.0f}")
plan = reachable_pick(obj)
if plan is None:
raise SkillError("I can't reach it safely.")
_guarded(_do_pick, obj, *plan)
log("holding it")
return obj
def place(x, y):
"""Put down what pick() holds at (x, y), then go home."""
return _place_first([(x, y)], "I can't reach that place safely.")
def put_down(back=False):
"""Put down what pick() holds: where it was picked (`back`) or at a free spot near there."""
if "top_mm" not in _held:
raise SkillError("I'm not holding anything I picked.")
xy = (_held["x"], _held["y"])
if back:
return _place_first([xy], "I can't reach that place safely.")
others = [o for o in look() if np.hypot(o["x"] - xy[0], o["y"] - xy[1]) >= CLUSTER_MM] # not the held one
tries = spots(xy, others)
if not tries:
raise SkillError("I can't find a free place to put it.")
return _place_first(tries, "I can't find a free place I can reach.")
def _place_first(tries, refusal):
"""Place at the first (x, y) of `tries` whose whole path passes IK; the rest of place() / put_down()."""
_cancel.clear()
if "top_mm" not in _held:
raise SkillError("I'm not holding anything I picked.")
start, joints = motion.tcp(), _joints()
carry = ik_chain([("carry", up(start, ABOVE_MM))], joints) # other turns start from up here, clear of
for xy in tries: # the table
rows = ik_chain(plan_place(*xy, _held["top_mm"], start=start, yaw=_held.get("yaw", 0.0)), joints)
if not rows[-1][3]:
_guarded(_do_place, [(r[0], r[1]) for r in rows])
log("done")
return xy
log(f"spot ({xy[0]:.0f}, {xy[1]:.0f}) refused at {rows[-1][0]}: {rows[-1][3]}")
opt = None if carry[-1][3] else next(place_options(*xy, _held["top_mm"], carry[-1][2]), None)
if opt:
_guarded(_line, "carry", carry[-1][1])
_guarded(place_turned, *opt)
log("done")
return xy
raise SkillError(refusal)
def move_object(name="cup", colour=None, to=None):
"""Pick `name` up and put it at `to` (x, y) or at a free spot. Everything is planned before anything moves."""
_cancel.clear()
seen = look()
obj = find(name, colour, seen)
log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f}")
xy, rows = plan_move(obj, to, seen)
log(f"placing at ({xy[0]:.0f}, {xy[1]:.0f}); plan of {len(rows)} waypoints passed")
waypoints = [(r[0], r[1]) for r in rows]
_guarded(_do_pick, obj, waypoints[:3], rows[0][2])
_guarded(_do_place, waypoints[3:])
log("done")
return xy
def _dry_run(name, to):
seen = look()
for o in seen:
log(f"seen {o['colour']} {o['name']} at ({o['x']:.0f}, {o['y']:.0f}) top {o['top_mm']} "
f"width {o['width_mm']} in {o['seen']}/{FRAMES} frames, spread {o['spread']} mm")
obj = find(name, None, seen)
log(f"picking {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f}")
try:
xy, rows = plan_move(obj, to, seen)
log(f"place spot ({xy[0]:.0f}, {xy[1]:.0f})")
except SkillError as e:
log(f"no plan: {e}")
return
for n, pose, j, err in rows:
print(f" {n:12s} flange {[round(v, 1) for v in pose[:3]]} joints {[round(v, 1) for v in j]} "
f"{'FAIL ' + err if err else 'ok'}")
if __name__ == "__main__":
a = sys.argv[1:]
to = None
if "--to" in a:
i = a.index("--to")
to, a = (float(a[i + 1]), float(a[i + 2])), a[:i] + a[i + 3:]
try:
if a[:1] == ["plan"]:
_dry_run(a[1] if len(a) > 1 else "cup", to)
elif a[:1] == ["pick"]:
pick(a[1] if len(a) > 1 else "cup")
elif a[:1] == ["move"]:
move_object(a[1] if len(a) > 1 else "cup", to=to)
else:
sys.exit(__doc__)
except SkillError as e:
sys.exit(f"refused: {e}")
except motion.MotionError as e:
sys.exit(f"motion failed: {e}")
except KeyboardInterrupt:
sys.exit("stopped")
+177
View File
@@ -0,0 +1,177 @@
"""Wave the hand when someone asks for it. A greeting never moves the arm.
The arm waves only from a known start pose (START_POSES: `look`, where the robot stands). It goes through the taught
poses ROUTE (first the hand away from the head, then up), swings one wrist joint about the last of them and comes back
the same way. Before anything moves, every joint move of that sequence is checked: joint limits, no joint turning
further than motion.MAX_TRAVEL, and at PATH_POINTS points along it (kine_forward) the gripper (flange -> grasp point ->
finger tips) stays HEAD_CLEAR_MM from the head's turning centre (vision/head_cam.py). Refused, with the reason in
English and Korean: the arm off or busy, the base driving, a task running, something in the hand, the arm anywhere
else (after free drive, in carry or give), a pose not taught, a move too near the head.
The Cobo π program hand_shaking.jks is not used: it ran from wherever the arm was and hit the head from `look`
(2026-10-21).
python manipulation/wave.py check # plan and check from where the arm is now; moves nothing
python manipulation/wave.py run # wave (slow; the owner at the STOP)
Teach the route first, arm moved by hand in Cobo π: python robot/motion.py teach wave_start / teach wave
"""
import sys
import numpy as np
from manipulation import skills
from robot import agv, arm, gripper, motion
from vision import calib, head_cam
START_POSES = ("look",) # the wave starts and ends only at one of these (motion.poses())
ROUTE = ("wave_start", "wave") # taught poses from the start: the hand away from the head, then raised
AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close
WAVE_JOINT = 4 # joint index swung at the raised pose (4 = J5); check on the first slow run
WAVE_DEG = 15.0 # deg each way from the raised pose
WAVE_SWINGS = 2 # times there and back
WAVE_SPEED = "slow" # motion.JOINT_SPEED; the route and the swings
PATH_POINTS = 21 # points checked (kine_forward) on every joint move
HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turning centre. Estimate: the head camera
# is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266
# Why Lumi does not wave, (English, Korean)
OFF = ("My arm is switched off, so I can't wave.", "팔이 꺼져 있어서 손을 흔들 수 없어요.")
BUSY = ("I'm busy with my arm right now.", "지금 팔로 하는 일이 있어요.")
DRIVING = ("I can't wave while I'm moving.", "움직이는 동안에는 손을 흔들 수 없어요.")
HOLDING = ("I'm holding something, so I won't wave.", "손에 물건을 들고 있어서 손을 흔들지 않을게요.")
UNKNOWN_POSE = ("My arm isn't in its usual place, so I won't wave. Please put it back first.",
"팔이 평소 자세가 아니어서 손을 흔들지 않을게요. 먼저 팔을 제자리로 해 주세요.")
NOT_TAUGHT = ("I haven't learned how to wave safely yet.", "아직 안전하게 손 흔드는 법을 배우지 못했어요.")
NEAR_HEAD = ("Waving would bring my hand too close to my head, so I won't.",
"손이 머리에 너무 가까워져서 손을 흔들지 않을게요.")
UNSURE = ("I can't check my arm right now, so I won't wave.", "지금 팔 상태를 확인할 수 없어서 손을 흔들지 않을게요.")
class WaveError(RuntimeError):
"""args: (English, Korean) reason."""
def log(*a):
print(*a, flush=True)
def _holding():
"""Is something in the hand? The fetch rule (fetch._in_hand): the task state first, then the torso camera, the
gripper's AI_1 when the camera can't tell. Only reads: fetch's own functions write its state file."""
from tasks import fetch
st = fetch.state()
if st.get("holding") or st.get("held_object"):
return True
try:
seen = skills.hand_sees()
except (skills.SkillError, ConnectionError, OSError, KeyError):
seen = "unknown"
return seen == "object" if seen != "unknown" else bool(gripper.state()["holding"])
def _seg_dist(c, a, b):
"""mm from point c to the segment a-b."""
ab = b - a
t = min(1.0, max(0.0, float((c - a) @ ab) / float(ab @ ab))) if ab @ ab else 0.0
return float(np.linalg.norm(c - (a + t * ab)))
def gripper_clearance(j, centre):
"""Smallest distance (mm) from `centre` to the gripper (flange -> grasp point -> finger tips) at joints j."""
c = skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"]
R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3], float)
g = f + R @ skills.GRASP_OFFSET
tip = g + R @ (skills.TIP_MM * skills.FINGER_DIR)
return min(_seg_dist(centre, f, g), _seg_dist(centre, g, tip))
def move_clearance(j0, j1, centre):
"""Smallest gripper distance (mm) to `centre` at PATH_POINTS points of the joint move j0 -> j1 (the controller
moves all joints together, in a straight line in joint space)."""
j0, j1 = np.array(j0, float), np.array(j1, float)
return min(gripper_clearance(j0 + (j1 - j0) * k / (PATH_POINTS - 1), centre) for k in range(PATH_POINTS))
def _at(now, pose):
return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) <= AT_POSE_DEG
def plan():
"""Joint targets of the whole wave from here, each move checked. Raises WaveError to refuse."""
from tasks import fetch
st = arm.cmd("get_robot_state")
if not (st.get("power") and st.get("enable")):
raise WaveError(*OFF)
if arm.program_state() != "idle" or fetch.state().get("status") in ("running", "waiting"):
raise WaveError(*BUSY)
if (agv.status() or {}).get("move_status") == "running":
raise WaveError(*DRIVING)
if _holding():
raise WaveError(*HOLDING)
now, poses = motion.joints(), motion.poses()
start = next((n for n in START_POSES if n in poses and _at(now, poses[n])), None)
if start is None:
log(f"wave refused: arm at {[round(v, 1) for v in now]}, not at {', '.join(START_POSES)}")
raise WaveError(*UNKNOWN_POSE)
if any(n not in poses for n in ROUTE):
log(f"wave refused: teach {', '.join(n for n in ROUTE if n not in poses)} first (robot/motion.py teach)")
raise WaveError(*NOT_TAUGHT)
route = [list(poses[n]) for n in ROUTE]
top, i = route[-1], WAVE_JOINT
swings = [top[:i] + [top[i] + s * WAVE_DEG] + top[i + 1:] for _ in range(WAVE_SWINGS) for s in (1, -1)]
seq, prev = [], now
for t in route + swings + [top] + route[-2::-1] + [poses[start]]:
motion.check(t)
t = motion.nearest(t, prev) # as move_joints will turn it
if max(abs(a - b) for a, b in zip(t, prev)) > motion.MAX_TRAVEL:
log(f"wave refused: {[round(v, 1) for v in prev]} -> {[round(v, 1) for v in t]} turns a joint too far")
raise WaveError(*NOT_TAUGHT)
seq.append(t)
prev = t
centre = head_cam.head_centre()
if centre is None:
raise WaveError(*UNSURE)
done = set()
for a, b in zip([now] + seq, seq):
key = frozenset((tuple(np.round(a, 1)), tuple(np.round(b, 1))))
if key in done: # the way back and the repeated swings: checked once
continue
done.add(key)
d = move_clearance(a, b, centre)
if d < HEAD_CLEAR_MM:
log(f"wave refused: {[round(v, 1) for v in a]} -> {[round(v, 1) for v in b]} brings the gripper "
f"{d:.0f} mm from the head (needs {HEAD_CLEAR_MM:.0f})")
raise WaveError(*NEAR_HEAD)
return seq
def wave(on_start=None):
"""Plan, check and wave; back at the start pose at the end. `on_start()` is called once the plan is checked.
Raises WaveError (refused) or motion.MotionError (stopped / failed while moving: the arm stays where it stopped)."""
try:
seq = plan()
except (motion.MotionError, skills.SkillError, ConnectionError, OSError, KeyError, ValueError) as e:
log(f"wave refused: {e}")
raise WaveError(*UNSURE) from e
log(f"wave: {len(seq)} joint moves, checked")
if on_start:
on_start()
for t in seq:
motion.move_joints(t, WAVE_SPEED)
if __name__ == "__main__":
what = sys.argv[1] if len(sys.argv) > 1 else "check"
try:
if what == "check":
print([[round(v, 1) for v in t] for t in plan()])
elif what == "run":
wave()
print("done")
else:
sys.exit(__doc__)
except WaveError as e:
sys.exit(f"refused: {e.args[0]}")
except KeyboardInterrupt:
print(motion.stop())
View File
+109
View File
@@ -0,0 +1,109 @@
"""Mobile base (AGV) over its TCP API (192.168.10.10:31001).
python robot/agv.py # status + markers
python robot/agv.py go point1 # drive to a marker (returns at once)
python robot/agv.py cancel
"""
import json
import socket
import sys
import uuid
AGV = ("192.168.10.10", 31001)
DOCK_FALLBACK = "충전위치로" # dock marker name on the old map; on any map the type-11 marker is used
def request(command, timeout=3.0):
tag = uuid.uuid4().hex
command += ("&" if "?" in command else "?") + f"uuid={tag}"
buf, dec = "", json.JSONDecoder()
with socket.create_connection(AGV, timeout=timeout) as s:
s.sendall(command.encode())
while True:
chunk = s.recv(65536)
if not chunk: # the base closed the connection: never loop forever
raise ConnectionError(f"AGV closed the connection ({command.split('?')[0]})")
buf += chunk.decode()
while buf.strip():
try:
msg, end = dec.raw_decode(buf.lstrip())
except json.JSONDecodeError:
break
buf = buf.lstrip()[end:]
if msg.get("uuid") == tag:
return msg
def status():
return request("/api/robot_status").get("results", {})
def dock_marker():
"""Name of the main charging-dock marker on the current map ("home"): of the type-11 markers the one with the
lowest dock number (num); None when there is none. Further docks keep their own names (dock2, ...)."""
docks = [(m.get("num", 1), name) for name, m in (request("/api/markers/query_list").get("results") or {}).items()
if m.get("key") == 11]
return min(docks)[1] if docks else None
def markers():
"""Marker names on the current map; the dock marker is called "home"."""
names = list((request("/api/markers/query_brief").get("results") or {}).keys())
dock = dock_marker()
return ["home" if n == dock else n for n in names]
def go(marker):
"""Start driving to a marker. Returns (ok, message)."""
marker = (dock_marker() or DOCK_FALLBACK) if marker == "home" else marker
if status().get("move_status") == "running":
request("/api/move/cancel")
r = request(f"/api/move?marker={marker}")
return r.get("status") == "OK", r.get("error_message") or r.get("status")
def go_point(x, y, theta):
"""Start driving to a map point (m, rad). Returns (ok, message)."""
if status().get("move_status") == "running":
request("/api/move/cancel")
r = request(f"/api/move?location={x:.3f},{y:.3f},{theta:.3f}")
return r.get("status") == "OK", r.get("error_message") or r.get("status")
def pose():
"""(x, y, theta) of the base on the map."""
p = status()["current_pose"]
return p["x"], p["y"], p["theta"]
def turn_by(angle_rad):
"""Turn in place by angle_rad (+ = left); the base plans it like a normal move."""
x, y, th = pose()
return go_point(x, y, (th + angle_rad + 3.14159265) % 6.2831853 - 3.14159265)
def probe(x, y):
"""(live, map): distance (m) from the map point (x, y) to the nearest obstacle the sensors see now and to the
nearest one on the map; inf when there is none in range."""
d = request(f"/api/map/distance_probe?x={x:.3f}&y={y:.3f}").get("results", {}).get("env_dist", {})
return tuple(v if v is not None and v >= 0 else float("inf") for v in (d.get("obstacle"), d.get("static")))
def clearance(x, y):
"""Distance (m) from the map point (x, y) to the nearest obstacle the sensors see now or the map holds."""
return min(probe(x, y))
def cancel():
return request("/api/move/cancel").get("status")
if __name__ == "__main__":
if len(sys.argv) > 2 and sys.argv[1] == "go":
print(go(sys.argv[2]))
elif len(sys.argv) > 1 and sys.argv[1] == "cancel":
print(cancel())
else:
st = status()
print({k: st.get(k) for k in ("move_status", "move_target", "charge_state", "power_percent", "current_pose")})
print("markers:", markers())
+88
View File
@@ -0,0 +1,88 @@
"""Run a Cobo π program on the arm over the controller's TCP command port 10001 (no SDK).
python robot/arm.py # state
python robot/arm.py run # play hand_shaking.jks once and wait
python robot/arm.py stop
"""
import json
import socket
import sys
import time
CONTROLLER = ("192.168.10.90", 10001)
WAVE = "hand_shaking.jks"
# The controller now and then closes the connection without a reply (seen on get_data, get_program_state,
# kine_inverse, stop_program, moveL, set_digital_output). Commands that only read are asked again, and so are those
# that set an absolute value: moves to an absolute target (relFlag 0) and setting an output; sent twice they do the
# same. Relative moves are never repeated here.
READ_ONLY = {"get_data", "get_joint_pos", "get_tcp_pos", "get_robot_state", "get_program_state", "get_loaded_program",
"kine_inverse", "kine_forward"}
ABSOLUTE_MOVES = {"moveL", "joint_move"}
SET_VALUE = {"set_digital_output", "stop_program"}
RETRIES, RETRY_S = 3, 0.2
def cmd(name, **args):
again = name in READ_ONLY or name in SET_VALUE or (name in ABSOLUTE_MOVES and args.get("relFlag") == 0)
tries = RETRIES if again else 1
for i in range(tries):
try:
return _send(name, args)
except (ConnectionError, OSError):
if i == tries - 1:
raise
time.sleep(RETRY_S)
def _send(name, args):
with socket.create_connection(CONTROLLER, timeout=10) as s:
s.sendall(json.dumps({"cmdName": name, **args}).encode())
buf = ""
while True:
chunk = s.recv(65536)
if not chunk: # the controller closed the connection: never loop forever
raise ConnectionError(f"arm controller closed the connection ({name})")
buf += chunk.decode()
try:
return json.loads(buf)
except json.JSONDecodeError:
continue
def ready():
"""True when the arm is powered, enabled and no program is running."""
r = cmd("get_robot_state")
return bool(r.get("power")) and bool(r.get("enable")) and cmd("get_program_state").get("programState") == "idle"
def program_state():
return cmd("get_program_state").get("programState")
def start(program=WAVE):
"""Load (if needed) and start a program; returns at once."""
if (cmd("get_loaded_program").get("programName") or "").lower() != program.lower():
if cmd("load_program", programName=program).get("errorCode") != "0":
raise RuntimeError(f"cannot load {program}")
if cmd("play_program").get("errorCode") != "0":
raise RuntimeError("play_program failed")
def stop():
return cmd("stop_program")
if __name__ == "__main__":
what = sys.argv[1] if len(sys.argv) > 1 else "state"
if what == "run":
if not ready():
sys.exit("arm not ready (power/enable off, or a program is running)")
start()
time.sleep(0.5)
while program_state() != "idle":
time.sleep(0.3)
print("done")
elif what == "stop":
print(stop())
else:
print(cmd("get_robot_state"), program_state(), cmd("get_loaded_program").get("programName"))
+112
View File
@@ -0,0 +1,112 @@
"""Writes every drive of the base to the log, whoever started it (dashboard, fetch, assistant): the start, where it
is on the way and how far it still has to go, standing still, the end (arrived / failed / cancelled), E-stop and
error codes. The base's own status is read once a second. api/server.py runs it; the lines show in the dashboard's
Settings -> Logs.
python robot/drive_log.py # watch and print here (Ctrl+C)
"""
import math
import time
from robot import agv
POLL_S = 1.0 # s between base status reads
PROGRESS_S = 5.0 # s between "on the way" lines
STILL_M = 0.05 # m; moving less than this ...
STILL_S = 5.0 # ... for this long while driving -> "standing still" (again every STILL_S)
STUCK_S = 15.0 # standing still this long -> "seems stuck" (shown among the errors)
OK_CODE = "00000000" # robot_status error_code when there is no error
class DriveLog:
"""Turns base status reads into log lines (update() returns the new ones)."""
def __init__(self, marker_xy):
self.marker_xy = marker_xy # f(name) -> (x, y) or None
self.drive = None # target, start time, start pose of the drive in progress
self.last_line = self.anchor = None # time of the last progress line; (x, y, t) of the last real move
self.flags = {} # error_code / estop / paused as last logged
def _where(self, p, target):
xy = self.marker_xy(target)
left = f", {math.hypot(xy[0] - p['x'], xy[1] - p['y']):.2f} m to go" if xy else ""
return f"at ({p['x']:.2f}, {p['y']:.2f}){left}"
def update(self, st, now):
out = []
for key, bad, on, off in (("error_code", lambda v: v not in (None, OK_CODE), "base error code {v}",
"base error code cleared"),
("estop_state", bool, "base E-stop pressed", "base E-stop released"),
("is_paused", bool, "base paused", "base running again")):
v = st.get(key)
if bad(v) != self.flags.get(key, False):
self.flags[key] = bad(v)
out.append(on.format(v=v) if bad(v) else off)
status, target, p = st.get("move_status"), st.get("move_target"), st.get("current_pose")
if p is None:
return out
running = status == "running"
if running and (self.drive is None or self.drive["target"] != target):
self.drive = {"target": target, "t0": now}
self.last_line, self.anchor = now, (p["x"], p["y"], now)
out.append(f"drive to {target}: started {self._where(p, target)}")
elif running:
moved = math.hypot(p["x"] - self.anchor[0], p["y"] - self.anchor[1])
if moved >= STILL_M:
self.anchor = (p["x"], p["y"], now)
still = now - self.anchor[2]
if still >= STILL_S and now - self.last_line >= STILL_S:
word = "seems stuck" if still >= STUCK_S else "standing still"
out.append(f"drive to {target}: {word} for {still:.0f} s {self._where(p, target)}")
self.last_line = now
elif still < STILL_S and now - self.last_line >= PROGRESS_S:
out.append(f"drive to {target}: on the way {self._where(p, target)}")
self.last_line = now
elif self.drive is not None:
took = now - self.drive["t0"]
word = {"succeeded": "arrived", "failed": "failed", "canceled": "cancelled"}.get(status, status)
out.append(f"drive to {self.drive['target']}: {word} after {took:.0f} s {self._where(p, self.drive['target'])}")
self.drive = None
return out
def marker_positions():
"""f(name) -> (x, y) of a marker on the current map; re-read when a name is not known yet."""
cache = {}
def xy(name):
if name not in cache:
try:
for n, m in (agv.request("/api/markers/query_list").get("results") or {}).items():
cache[n] = (m["pose"]["position"]["x"], m["pose"]["position"]["y"])
except (ConnectionError, OSError, KeyError):
pass
cache.setdefault(name, None) # a map point's generated name: no marker
return cache[name]
return xy
def watch(log=print):
d, down = DriveLog(marker_positions()), False
while True:
try:
st = agv.status()
except (ConnectionError, OSError):
if not down:
log("base not answering")
down = True
time.sleep(POLL_S)
continue
if down:
log("base answering again")
down = False
for line in d.update(st, time.time()):
log(line)
time.sleep(POLL_S)
if __name__ == "__main__":
try:
watch(lambda line: print(time.strftime("%H:%M:%S"), line, flush=True))
except KeyboardInterrupt:
pass
+80
View File
@@ -0,0 +1,80 @@
"""The Zimmer electric gripper on the arm's tool connector (TIO), driven by two digital outputs.
Wiring found 2026-10-13 (Cobo π → I/O → Tool(S), outputs set to PNP):
DO_1 on -> the gripper closes, DO_2 on -> it opens (a stroke takes ~1 s)
AI_1 -> finger position: ~160 open, ~4100-4200 closed on nothing, ~3500 closed on a cup (cup test
11:39:12); in between while moving. A close runs to the end once started: DO_1 off half way
(AI_1 2730) still ended at 4190 (2026-10-19), so the fingers can't be stopped on a soft cup.
A soft plastic cup squeezed flat reads like "empty" (3 of 4 cup closes reached ~4150).
DI_1 -> optical sensor under the gripper: 1 while something is below it, not between the fingers (PNP);
a held object shows only in AI_1 (gap_mm)
Only one output may be on at a time: both on = close and open at once.
python robot/gripper.py # state
python robot/gripper.py open
python robot/gripper.py close
"""
import sys
import time
from robot import arm
TOOL = 1 # set_digital_output type: 0 cabinet, 1 tool (TIO), 2 extended
CLOSE_DO, OPEN_DO = 0, 1 # DO_1, DO_2 (0-based)
CLOSED_AI = 400 # AI_1 above this = closed on something (open reads 130-165; an 82 mm metal cup
# held in the cup fingers reads ~2200-2300, 2026-10-13)
EMPTY_AI = 3900 # closed above this = nothing between the fingers (empty reads 4100-4200, noise +-50)
AI_OPEN, AI_SHUT = 140.0, 4160.0 # AI_1 fully open / closed on nothing (2026-10-19)
# inner gap (mm) between the fingers, (open, closed), measured with a tape 2026-10-19 (docs/gripper/README.md); the gap
# is taken as linear in AI_1: an 82 mm metal cup read 2189-2310 (2026-10-13), the line gives 81-83 mm at the belly
GAP_MM = {"tips": (88.0, 59.0), "belly": (96.0, 70.0), "neck": (73.0, 47.0), "shank": (66.0, 39.0)}
MOVE_S = 1.5 # s a full stroke takes (measured ~1 s)
SENSOR_DI = 0 # DI_1
READ_TRIES, READ_GAP_S = 5, 0.1 # get_data now and then answers without the tool I/O: ask again
def state():
for _ in range(READ_TRIES):
d = arm.cmd("get_data")
if all(k in d for k in ("tio_ain", "tio_din", "tio_dout")):
break
time.sleep(READ_GAP_S)
else:
raise ConnectionError("the arm controller sends no tool I/O")
ai = d["tio_ain"][0]
return {"closed": ai > CLOSED_AI, "holding": CLOSED_AI < ai < EMPTY_AI, "object_in_front": bool(d["tio_din"][SENSOR_DI]),
"ai": d["tio_ain"], "do": d["tio_dout"], "di": d["tio_din"], "gap_mm": round(gap_mm(ai))}
def gap_mm(ai, where="belly"):
"""Inner gap (mm) between the fingers at `where` (GAP_MM) for an AI_1 reading: the held object's width there."""
opened, closed = GAP_MM[where]
f = min(1.0, max(0.0, (ai - AI_OPEN) / (AI_SHUT - AI_OPEN)))
return opened + f * (closed - opened)
def _out(index, value):
r = arm.cmd("set_digital_output", type=TOOL, index=index, value=int(value))
if r.get("errorCode") != "0":
raise RuntimeError(f"set_digital_output failed: {r}")
def close(wait=True):
_out(OPEN_DO, 0) # never both on
_out(CLOSE_DO, 1)
if wait:
time.sleep(MOVE_S)
return state()
def open_(wait=True):
_out(CLOSE_DO, 0)
_out(OPEN_DO, 1)
if wait:
time.sleep(MOVE_S)
return state()
if __name__ == "__main__":
what = sys.argv[1] if len(sys.argv) > 1 else "state"
print({"open": open_, "close": close}.get(what, state)())
+73
View File
@@ -0,0 +1,73 @@
"""Turn Lumi's head (body HTTP API on the arm/body controller).
python robot/head.py # print lift, waist, head yaw, head pitch
python robot/head.py 10 # head yaw to +10 deg (slow), other joints unchanged
python robot/head.py 10 5 # head yaw +10 deg, head pitch +5 deg
python robot/head.py 30 --vel 60 # try another speed (speed ratio %, 1-100)
"""
import json
import sys
import threading
import urllib.request
BODY = "http://192.168.10.90:5000/api/extaxis"
YAW_LIMIT = 60.0 # deg; we keep the head well inside its +-180 range
PITCH_RANGE = (-5.0, 35.0) # deg, hardware range
VEL = 40 # speed ratio %, 1-100 (was 15: too slow to follow a visitor)
ACC = 40 # acceleration ratio %, 1-100
# Temporary (2026-10-20): the head camera's cable is too short, a higher lift pulls it out. Back to 250 mm (what
# tasks/fetch.py used before; the body API allows 300) when the longer cable is in.
LIFT_MAX_MM = 105.0
# [lift mm, waist, head yaw, head pitch] limits of the body API (docs/03), the lift held to LIFT_MAX_MM. The controller
# drops a whole moveto when any value is outside, and its own encoders read a little past the ends (pitch -5.003 at
# the bottom stop).
AXIS_LIMITS = ((0.0, LIFT_MAX_MM), (-140.0, 140.0), (-180.0, 180.0), (-5.0, 35.0))
_one = threading.Lock() # one moveto at a time: overlapping calls hang the body API
owners = () # threads that own the body now (tasks/follow.py); empty: anyone may move it
def _call(path, body=None, timeout=2):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(f"{BODY}/{path}", data=data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def moveto(pos, vel=VEL, acc=ACC, timeout=30):
"""Move all four body joints; every value is clamped into AXIS_LIMITS. Blocks until the motion ends (and while
another thread's moveto runs). None, nothing sent, when other threads own the body (`owners`)."""
if owners and threading.current_thread() not in owners:
return None # ponytail: skipped silently, the owner turns it back
pos = [max(lo, min(hi, float(p))) for p, (lo, hi) in zip(pos, AXIS_LIMITS)]
with _one:
if not all(j["enable"] for j in _call("status")): # off after a controller power cycle; moveto needs them on
_call("enable", {"enable": 1})
return _call("moveto", {"pos": pos, "vel": vel, "acc": acc}, timeout=timeout)
def status():
"""[lift mm, waist deg, head yaw deg, head pitch deg]"""
return [j["pos"] for j in _call("status")]
def turn(yaw, pitch=None, vel=VEL, acc=ACC):
"""Move the head; blocks until the motion ends. Returns the controller's reply."""
lift, waist, _, cur_pitch = status()
yaw = max(-YAW_LIMIT, min(YAW_LIMIT, yaw))
pitch = cur_pitch if pitch is None else max(PITCH_RANGE[0], min(PITCH_RANGE[1], pitch))
return moveto([lift, waist, yaw, pitch], vel, acc)
if __name__ == "__main__":
args = sys.argv[1:]
vel = VEL
if "--vel" in args:
i = args.index("--vel")
vel = float(args[i + 1])
del args[i:i + 2]
if not args:
print(dict(zip(["lift_mm", "waist", "head_yaw", "head_pitch"], (round(p, 2) for p in status()))))
else:
print(turn(float(args[0]), float(args[1]) if len(args) > 1 else None, vel))
print("now:", [round(p, 2) for p in status()])
+245
View File
@@ -0,0 +1,245 @@
"""Checked arm motion over the controller's TCP command port (10001, JSON, no SDK): named poses, joint moves,
straight-line TCP moves, stop.
Every move is checked before it is sent: joint limits with a margin, and for linear moves an IK solution
(the controller's kine_inverse) that does not swing J1 / J4 / J6 around. Moves wait until the arm is there,
and return early with an error when STOP was pressed or the controller stopped the arm.
python robot/motion.py # joints, TCP, named poses
python robot/motion.py go tuck [normal] # move to a named pose (slow by default)
python robot/motion.py teach ready # save the arm's current joints as a named pose (move it in Cobo π first)
python robot/motion.py line 0 0 30 # straight TCP move by dx dy dz mm (base frame), slow
python robot/motion.py stop
Poses taught with `teach` are kept in arm_poses.json next to this file.
"""
import json
import sys
import threading
import time
from pathlib import Path
from robot import arm
ROOT = Path(__file__).resolve().parents[1] # the project folder
POSES_FILE = ROOT / "data" / "arm_poses.json"
TUCK = [179.3, -88.6, -13.9, -15.8, -14.5, -121.3] # deg, arm folded beside the column (fits doorways)
LIMITS = [360, 125, 130, 360, 120, 360] # deg, ± factory range per joint (docs/01_HARDWARE.md)
LIMIT_MARGIN = 5.0 # deg kept away from every limit
JOINT_SPEED = {"slow": 10.0, "normal": 25.0} # deg/s
LINEAR_SPEED = {"slow": 20.0, "normal": 50.0} # mm/s
ACCEL_FACTOR = 3.0 # accel = speed x this (per s)
MAX_FLIP = 90.0 # deg; an IK answer turning J1 / J4 / J6 more than this is refused
MAX_TRAVEL = 200.0 # deg; a joint move turning any joint further is refused
FULL_TURN = (0, 3, 5) # J1, J4, J6: ±360 joints; a target and target ± 360 are the same pose
AT_JOINT_DEG = 0.3 # arrived when every joint is this close ...
AT_TCP_MM = 1.0 # ... or the TCP this close (linear moves)
POLL_S = 0.1
EXTRA_S = 10.0 # s allowed on top of 3x the planned move time
STILL_S = 2.0 # s without joint motion (and not there) -> the move ended short
STILL_DEG = 0.05 # joint change that counts as motion
BLIND_S = 1.0 # s without a valid state reply while moving -> stop the arm
_stopped = threading.Event() # set by stop(): a waiting move gives up
class MotionError(RuntimeError):
pass
def _read(name, key):
"""A value read from the controller. It now and then answers with another command's reply (get_data or
get_robot_state to get_joint_pos, 2026-10-16): ask again."""
for _ in range(arm.RETRIES):
r = arm.cmd(name)
if key in r:
return r[key]
time.sleep(arm.RETRY_S)
raise MotionError(f"{name} failed: {r.get('errorMsg') or r.get('cmdName') or r}")
def joints():
return _read("get_joint_pos", "joint_pos")
def tcp():
return _read("get_tcp_pos", "tcp_pos")
def poses():
"""Named poses: tuck plus everything taught."""
try:
taught = json.loads(POSES_FILE.read_text())
except FileNotFoundError:
taught = {}
return {"tuck": TUCK, **taught}
def teach(name):
"""Save the current joints as pose `name`."""
if name == "tuck":
raise MotionError("tuck is fixed in motion.py")
check(j := [round(v, 2) for v in joints()])
taught = {k: v for k, v in poses().items() if k != "tuck"}
taught[name] = j
POSES_FILE.write_text(json.dumps(taught, indent=1))
return j
def check(target):
"""Raise MotionError if a joint target is out of range (with LIMIT_MARGIN)."""
if len(target) != 6:
raise MotionError(f"need 6 joints, got {len(target)}")
for i, (v, lim) in enumerate(zip(target, LIMITS)):
if abs(v) > lim - LIMIT_MARGIN:
raise MotionError(f"J{i + 1} {v:.1f} deg is beyond ±{lim - LIMIT_MARGIN:.0f}")
def _ready():
st = arm.cmd("get_robot_state")
if not (st.get("power") and st.get("enable")):
raise MotionError("arm is not powered / enabled")
if arm.program_state() != "idle":
raise MotionError("a Cobo π program is running")
def _wait(arrived, planned_s):
"""Wait while the arm moves. Big joint moves run slower than speed / travel suggests (measured: 157 deg
of J6 at 10 deg/s took well over 21 s), so the limit is generous; a move that stops short is caught by
STILL_S instead."""
t0 = last_move = last_seen = time.time()
last = None
while time.time() - t0 < 3 * planned_s + EXTRA_S:
if _stopped.is_set():
raise MotionError("stopped")
try:
d = arm.cmd("get_data")
except (ConnectionError, OSError):
d = {}
if "joint_actual_position" not in d: # the controller now and then answers a poll with nothing
if time.time() - last_seen > BLIND_S:
stop()
raise MotionError("lost the arm state while moving - stopped")
time.sleep(POLL_S)
continue
last_seen = time.time()
if d.get("protective_stop") or d.get("emergency_stop"):
raise MotionError("the controller stopped the arm (protective / emergency stop)")
if d.get("inpos") and arrived(d):
return d
j = d["joint_actual_position"]
if last is None or max(abs(a - b) for a, b in zip(j, last)) > STILL_DEG:
last, last_move = j, time.time()
elif time.time() - last_move > STILL_S and time.time() - t0 > STILL_S + 1:
raise MotionError("the arm stopped before the target")
time.sleep(POLL_S)
stop()
raise MotionError(f"not there after {time.time() - t0:.0f} s - stopped")
def nearest(target, start):
"""For the ±360 joints use target or target ± 360, whichever is closest to where the joint is now:
the same pose, without spinning the arm a full turn around the column."""
out = list(target)
for i in FULL_TURN:
lim = LIMITS[i] - LIMIT_MARGIN
options = [v for v in (target[i] - 360, target[i], target[i] + 360) if abs(v) <= lim]
out[i] = min(options, key=lambda v: abs(v - start[i]))
return out
def move_joints(target, speed="slow", wait=True):
"""Joint move to absolute angles (deg). Returns the joints reached (or the target if wait=False)."""
check(target)
_ready()
deg_s = JOINT_SPEED[speed]
start = joints()
target = nearest(target, start)
for i, (a, b) in enumerate(zip(target, start)):
if abs(a - b) > MAX_TRAVEL:
raise MotionError(f"J{i + 1} would turn {a - b:+.0f} deg - refused")
travel = max(abs(a - b) for a, b in zip(target, start))
_stopped.clear()
r = arm.cmd("joint_move", relFlag=0, jointPosition=list(target), speed=deg_s, accel=deg_s * ACCEL_FACTOR)
if r.get("errorCode") != "0":
raise MotionError(f"joint_move refused: {r.get('errorMsg') or r}")
if not wait:
return list(target)
d = _wait(lambda d: max(abs(a - b) for a, b in zip(d["joint_actual_position"], target)) < AT_JOINT_DEG,
travel / deg_s)
return d["joint_actual_position"]
def go(name, speed="slow", wait=True):
p = poses()
if name not in p:
raise MotionError(f"no pose {name!r} (known: {', '.join(p)})")
return move_joints(p[name], speed, wait)
def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=False):
"""Straight TCP move to `target` [x, y, z mm, rx, ry, rz deg] or by `delta` (dx, dy, dz mm), base frame.
The end pose is checked with the controller's IK first. `path_checked`: the caller checked the whole line in
small steps (fetch._line_rows), so a big J1 / J4 / J6 turn over it is a real one, not another IK branch."""
now_j, now_p = joints(), tcp()
if target is None:
target = [now_p[i] + (delta[i] if i < len(delta) else 0.0) for i in range(3)] + list(now_p[3:])
for _ in range(3): # the controller now and then answers "0" without the joints: ask again
ik = arm.cmd("kine_inverse", jointPosition=now_j, cartPosition=list(target))
if "jointPosition" in ik or ik.get("errorCode") not in ("0", None):
break
time.sleep(0.2)
if "jointPosition" not in ik:
raise MotionError(f"no IK solution for {[round(v, 1) for v in target]}: {ik.get('errorMsg') or ik}")
end_j = ik["jointPosition"][:6] # some answers carry a 7th (external axis) value
check(end_j)
for i in () if path_checked else (0, 3, 5):
if abs(end_j[i] - now_j[i]) > MAX_FLIP:
raise MotionError(f"J{i + 1} would turn {end_j[i] - now_j[i]:+.0f} deg - refused")
_ready()
mm_s = LINEAR_SPEED[speed]
dist = sum((a - b) ** 2 for a, b in zip(target[:3], now_p[:3])) ** 0.5
_stopped.clear()
r = arm.cmd("moveL", relFlag=0, cartPosition=list(target), speed=mm_s, accel=mm_s * ACCEL_FACTOR)
if r.get("errorCode") != "0":
raise MotionError(f"moveL refused: {r.get('errorMsg') or r}")
if not wait:
return list(target)
d = _wait(lambda d: sum((a - b) ** 2 for a, b in zip(d["actual_position"][:3], target[:3])) ** 0.5 < AT_TCP_MM,
dist / mm_s)
return d["actual_position"]
def stop():
"""Stop any arm motion (also a running Cobo π program)."""
_stopped.set()
for _ in range(2): # the controller stops the arm but sometimes closes the connection without a reply
try:
return arm.cmd("stop_program")
except ConnectionError:
pass
return {"sent": True, "reply": None}
if __name__ == "__main__":
a = sys.argv[1:]
try:
if not a:
print("joints", [round(v, 2) for v in joints()])
print("tcp ", [round(v, 1) for v in tcp()])
for k, v in poses().items():
print(f"pose {k:8s}", v)
elif a[0] == "go":
print(go(a[1], a[2] if len(a) > 2 else "slow"))
elif a[0] == "teach":
print(a[1], teach(a[1]))
elif a[0] == "line":
print(move_linear(delta=[float(v) for v in a[1:4]]))
elif a[0] == "stop":
print(stop())
else:
sys.exit(__doc__)
except KeyboardInterrupt:
print(stop())
except MotionError as e:
sys.exit(f"refused / failed: {e}")
+115
View File
@@ -0,0 +1,115 @@
"""Where to drive to reach a person: a free spot about STOP_DIST in front of them that the base can get to.
The base's own /api/map/accessible_point_query answers every point unchanged, so the check is done here
on the map picture: free cells (white) that are at least ROBOT_RADIUS from any wall or unknown area, and
connected to where the robot stands now. Among those, the spot nearest to "STOP_DIST before the person on
the line from the robot" wins; the robot then faces the person.
python robot/nav.py 1.0 2.0 # best spot to reach a person at map x=1.0, y=2.0 from where the robot is
"""
import math
import sys
import urllib.request
import cv2
import numpy as np
from robot import agv
AGV_WEB = "http://192.168.10.10:9001"
STOP_DIST = 1.0 # m between the robot centre and the person
RING = (0.9, 1.6) # m, distances from the person that are tried
ROBOT_RADIUS = 0.35 # m of clearance needed (base 0.54 m wide + the arm)
CLOSE_ENOUGH = 1.3 # m; nearer than this the robot does not move
_map = {}
def load_map():
"""Current map: dict(name, res, ox, oy, h, clear (bool mask), comp (component ids))."""
cur = agv.request("/api/map/get_current_map")["results"]
key = (cur["map_name"], cur["floor"])
if _map.get("key") != key:
url = f"{AGV_WEB}/maps/{urllib.request.quote(cur['map_name'])}/{cur['floor']}/map.png"
img = cv2.imdecode(np.frombuffer(urllib.request.urlopen(url, timeout=10).read(), np.uint8),
cv2.IMREAD_GRAYSCALE)
info = cur["info"]
res = info["resolution"]
free = (img > 240).astype(np.uint8)
clearance = cv2.distanceTransform(free, cv2.DIST_L2, 5) * res
clear = clearance >= ROBOT_RADIUS
_, comp = cv2.connectedComponents(clear.astype(np.uint8), connectivity=8)
_map.update(key=key, res=res, ox=info["origin_x"], oy=info["origin_y"], h=img.shape[0], w=img.shape[1],
clear=clear, comp=comp, free=free.astype(bool))
return _map
def _cell(m, x, y):
return int((x - m["ox"]) / m["res"]), int(m["h"] - (y - m["oy"]) / m["res"])
def _robot_component(m, x, y):
"""Component id of the robot's place (or of the nearest clear cell within 0.6 m: it may stand near a wall)."""
cx, cy = _cell(m, x, y)
r = int(0.6 / m["res"])
best = None
for dy in range(-r, r + 1, 2):
for dx in range(-r, r + 1, 2):
px, py = cx + dx, cy + dy
if 0 <= px < m["w"] and 0 <= py < m["h"] and m["clear"][py, px]:
d = dx * dx + dy * dy
if best is None or d < best[0]:
best = (d, m["comp"][py, px])
return None if best is None else best[1]
def approach(person_x, person_y, robot=None):
"""(x, y, theta) to drive to, "close" if already near enough, or None if no reachable spot."""
rx, ry, _ = robot or agv.pose()
if math.hypot(person_x - rx, person_y - ry) <= CLOSE_ENOUGH:
return "close"
m = load_map()
comp = _robot_component(m, rx, ry)
if comp is None:
return None
toward = math.atan2(ry - person_y, rx - person_x) # from the person back to the robot
ideal = (person_x + STOP_DIST * math.cos(toward), person_y + STOP_DIST * math.sin(toward))
best = None
for dist in np.arange(RING[0], RING[1] + 1e-6, 0.1):
for a in np.radians(np.arange(0, 360, 10)):
gx, gy = person_x + dist * math.cos(a), person_y + dist * math.sin(a)
px, py = _cell(m, gx, gy)
if not (0 <= px < m["w"] and 0 <= py < m["h"]) or not m["clear"][py, px] or m["comp"][py, px] != comp:
continue
score = math.hypot(gx - ideal[0], gy - ideal[1])
if best is None or score < best[0]:
best = (score, gx, gy)
if best is None:
return None
_, gx, gy = best
return gx, gy, math.atan2(person_y - gy, person_x - gx)
def reachable(x, y, robot=None):
"""True when the base can stand at map (x, y): a free cell, next to (0.6 m) the open area the robot is in.
Near walls and furniture is allowed: that is where it stands to reach a table."""
m = load_map()
px, py = _cell(m, x, y)
if not (0 <= px < m["w"] and 0 <= py < m["h"]) or not m["free"][py, px]:
return False
rx, ry, _ = robot or agv.pose()
here = _robot_component(m, x, y)
return here is not None and here == _robot_component(m, rx, ry)
def person_on_map(distance_m, angle_deg, waist_deg=0.0, robot=None):
"""Map position of a person seen at distance / angle (deg, + left, waist frame) from the robot."""
rx, ry, th = robot or agv.pose()
a = th + math.radians(angle_deg + waist_deg)
return rx + distance_m * math.cos(a), ry + distance_m * math.sin(a)
if __name__ == "__main__":
x, y = float(sys.argv[1]), float(sys.argv[2])
print("robot", agv.pose())
print("drive to", approach(x, y))
View File
+2432
View File
File diff suppressed because it is too large Load Diff
+264
View File
@@ -0,0 +1,264 @@
"""Follow a person with the base: "follow me" ... "stop" (lumi.py follow_me).
The person is a track of the assistant's Vision; `see()` gives (distance m, angle deg + left, age s) or None once the
track is gone, `people()` [(see, distance, angle, age)] of everyone in view: a track lost is swapped for a fresh one
where the person was last (re-lock). The head turns toward the person (only this task moves the body meanwhile:
head.owners), the base turns after it, so they stay in view when they walk to the side or behind. The base is driven with joy_control (one command lasts 0.5 s: a stuck loop stops the base by itself),
the arm in look and the waist at the front as for every fetch drive. Every command is checked first: where the base
and the arm would be BRAKE_S later must be clear (lidar + map, agv.clearance).
stop() from any thread: the event is set and the base is sent 0 at once
"""
import math
import re
import threading
import time
import traceback
import numpy as np
from robot import agv, head, motion
from tasks import fetch
FOLLOW_GAP_M = 1.0 # m; keep this far from the person (camera distance); nearer: stand still
FOLLOW_MAX_MS = 0.15 # m/s; forward speed cap (estimate, tune live)
SPEED_GAIN = 0.8 # m/s per m the person is further than FOLLOW_GAP_M
ACCEL_MS2 = 0.4 # m/s^2; speeding up at most this fast (slowing down at once)
TURN_GAIN = 1.0 # rad/s per rad the person is off to the side
TURN_MAX_RS = 0.5 # rad/s; turn speed cap (joy_control takes up to 1.0)
TURN_DEAD_DEG = 5.0 # deg; the person this near the middle: no turn
TURN_ONLY_DEG = 30.0 # deg; the person further aside: turn on the spot first, no forward
STALE_S = 0.5 # s; a sighting older than this: stand still and wait for a new one
LOST_S = 2.0 # s without a sighting -> "I lost you" (lumi.Vision drops a track after its own LOST_S, 2 s)
BRAKE_S = 0.5 # s; the base and the arm must be clear where this command would take them by then
ARM_CLEAR_M = fetch.ARM_CLEAR_M # m; arm points kept this far from anything the lidar / map shows
BASE_CLEAR_M = fetch.BASE_HALF_M + fetch.CLEAR_M # m; base centre kept this far, unless it gets further away
TICK_S = 0.1 # s between commands (joy_control wants > 2 Hz)
JOIN_S = 2.0 # s a new "follow me" waits for the old loop to end
RELOCK_DEG = 25.0 # deg; a fresh track this near the lost person's last angle is taken as them (estimate)
RELOCK_M = 0.8 # m; ... and this near their last distance (estimate)
HEAD_YAW_MAX = 90.0 # deg; the head turns toward the person up to this far (+ left; body API allows 180)
HEAD_PITCH = 10.0 # deg; head pitch while following, a little up toward a standing person (as "look at me")
HEAD_STEP_DEG = 5.0 # deg; a new head move only when the person is this far from where the head was sent
HEAD_VEL = 50 # speed ratio %; the head is at its full speed from 50 (audio/sing.py, measured)
HEAD_TIMEOUT_S = 5 # s; one head move (90 deg at ~40 deg/s takes ~2.5 s)
CHARGER = ("I'm on the charger, I can't follow you from here.", "충전 중이라 따라갈 수 없어요.")
ARM_OFF = ("My arm is switched off, so I can't drive safely. Please enable it.",
"팔이 꺼져 있어서 안전하게 이동할 수 없어요. 팔을 켜 주세요.")
ARM_BUSY = ("A program is running on my arm, so I can't follow you.", "팔에서 프로그램이 실행 중이라 따라갈 수 없어요.")
LOST = ("I lost you, so I stopped. Stand in front of me and say follow me again.",
"놓쳐서 멈췄어요. 제 앞에 서서 다시 따라오라고 말해 주세요.")
NO_ARM = ("My arm is not answering, so I can't drive safely.", "팔이 응답하지 않아서 안전하게 이동할 수 없어요.")
_stop = threading.Event()
_send = threading.Lock() # a command and the stop never cross: after stop() no drive command goes out
_thread = None
STOP_WORDS = re.compile(r"\b(stop|halt|freeze|enough|wait|hold on|stay(?! with)|don'?t (move|follow)|no more|"
r"that'?s (enough|far enough|it))\b|멈춰|그만|정지|스톱|거기 ?(있어|서|계세요|있으세요)|기다려|"
r"여기 ?(있어|서)|따라오지 ?마|됐어|^\s*서[\s,!.]*$", re.I) # end following (only while it runs)
def stop_word(text):
"""A word that ends following ("stop", "wait", "that's enough", "거기 있어", "기다려")."""
return bool(STOP_WORDS.search(text or ""))
def running():
return _thread is not None and _thread.is_alive()
def _joy(v, w):
agv.request(f"/api/joy_control?linear_velocity={v:.3f}&angular_velocity={w:.3f}")
def stop():
"""End following at once: the base gets 0 now. True when it was following."""
was = running()
with _send:
_stop.set()
try:
_joy(0.0, 0.0)
except (ConnectionError, OSError) as e:
fetch.log(f"follow: stop command failed: {e}")
return was
def speeds(distance, angle_deg, v_last, dt=TICK_S):
"""(v m/s, w rad/s) toward a person `distance` m away at `angle_deg` (+ left); never forward inside the gap."""
if distance <= FOLLOW_GAP_M:
return 0.0, 0.0 # close enough: stand still (no turn: the arm sweeps)
a = math.radians(angle_deg)
w = 0.0 if abs(angle_deg) < TURN_DEAD_DEG else max(-TURN_MAX_RS, min(TURN_MAX_RS, TURN_GAIN * a))
v = 0.0 if abs(angle_deg) > TURN_ONLY_DEG else min(FOLLOW_MAX_MS, SPEED_GAIN * (distance - FOLLOW_GAP_M),
v_last + ACCEL_MS2 * dt)
return max(0.0, v), w
def blocked(v, w, arm_pts):
"""True when the base or the arm would come too close to something within BRAKE_S at (v, w)."""
x, y, th = agv.pose()
th2 = th + w * BRAKE_S
x2, y2 = x + v * BRAKE_S * math.cos(th), y + v * BRAKE_S * math.sin(th)
if v > 0:
ahead = agv.clearance(x2, y2)
if ahead < BASE_CLEAR_M and ahead < agv.clearance(x, y):
fetch.log(f"follow: an obstacle {ahead:.2f} m from the base's way")
return True
c, s = math.cos(th2), math.sin(th2)
for p in arm_pts:
px, py = x2 + c * p[0] - s * p[1], y2 + s * p[0] + c * p[1]
if agv.clearance(px, py) < ARM_CLEAR_M:
fetch.log(f"follow: my arm would hit something at ({px:.2f}, {py:.2f})")
return True
return False
def ready():
"""Why following can't start now as (en, ko), None when it can. The arm must be able to go to look, or be there
already: then it may stay switched off (it does not move while following)."""
if fetch._charging():
return CHARGER
try:
if fetch._at_pose(fetch._look()):
return None
motion._ready()
except motion.MotionError as e:
fetch.log(f"follow: the arm can't go to look: {e}")
return ARM_BUSY if "program" in str(e) else ARM_OFF
except Exception as e: # the controller does not answer
fetch.log(f"follow: the arm does not answer: {e!r}")
return NO_ARM
return None
def prepare():
"""Arm to look, waist to the front (as before every fetch drive). The head stays where it is: it is on the person
already (the track is seen), and ahead they may be out of view (lost at once, 2026-10-21). Returns the arm's points (m, base
frame) that stick out past the base, [] when the arm's place on the base is not measured. FetchError when it
must not drive."""
why = ready()
if why:
raise fetch.FetchError(*why)
fetch._stop.clear() # a stop said earlier must not end this one
fetch._pose(fetch._look())
fetch._waist_front()
if fetch.arm_yaw() is None:
fetch.log("follow: the arm's place on the base is not measured: only the base is checked")
return []
return [np.asarray(p, float) for p in fetch.arm_points()]
def _relock(people, last):
"""The see() of the fresh track nearest to where the followed person was last (distance, angle), None when
nobody is near. ponytail: by position only, appearance (reid) would tell two people apart."""
d0, a0 = last
near = [(abs(a - a0), see) for see, d, a, age in people()
if age < STALE_S and abs(a - a0) <= RELOCK_DEG and abs(d - d0) <= RELOCK_M]
return min(near, key=lambda n: n[0], default=(0, None))[1]
def _head_follow(target, done, lift, waist):
"""Turn the head to target[0] (yaw, pitch) whenever it is HEAD_STEP_DEG from where it was sent last. One moveto
at a time, from this thread only: overlapping calls hang the body API."""
sent = None
while not done.is_set():
t = target[0]
if t is None or sent is not None and max(abs(t[0] - sent[0]), abs(t[1] - sent[1])) < HEAD_STEP_DEG:
done.wait(TICK_S)
continue
try:
head.moveto([lift, waist, *t], vel=HEAD_VEL, acc=HEAD_VEL, timeout=HEAD_TIMEOUT_S)
sent = t
except (ConnectionError, OSError, ValueError, KeyError) as e:
fetch.log(f"follow: head error {e!r}")
done.wait(1.0)
def _run(see, say, people):
"""The loop: until stop(), lost, or something in the way. Any failure ends with the base at 0 and a reason said."""
v, turning = 0.0, False
done, target = threading.Event(), [None]
head.owners = (threading.current_thread(),)
try:
arm_pts = prepare()
lift, waist = head.status()[:2]
head_thread = threading.Thread(target=_head_follow, args=(target, done, lift, waist), daemon=True,
name="follow head")
head.owners += (head_thread,)
head_thread.start()
seen_t, last = time.time(), None
while not _stop.is_set():
got = see()
now = time.time()
if (got is None or got[2] >= STALE_S) and last and people:
new = _relock(people, last)
if new is not None:
fetch.log(f"follow: re-locked onto the person at {last[1]:+.0f} deg")
see, got = new, new()
if got is not None and got[2] < STALE_S:
seen_t, last = now - got[2], got[:2]
cmd = speeds(got[0], got[1], v)
target[0] = (max(-HEAD_YAW_MAX, min(HEAD_YAW_MAX, got[1])), HEAD_PITCH)
else: # stale or gone (Vision drops a track unseen for 2 s)
if now - seen_t >= LOST_S:
fetch.log("follow: lost the person")
fetch._say(say, *LOST)
return
cmd = (0.0, 0.0)
spot = cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind)
if spot and not turning:
hit = fetch.turn_hits(got[1]) # the arm's whole sweep toward them
if hit is not None:
fetch.log(f"follow: turning {got[1]:+.0f} deg my arm would hit something at "
f"({hit[0]:.2f}, {hit[1]:.2f})")
fetch._say(say, "My arm can't turn here, something is in its way.",
"팔이 부딪힐 수 있어서 돌 수 없어요.")
return
turning = spot
if cmd != (0.0, 0.0) and blocked(*cmd, arm_pts):
fetch._say(say, "Something is in my way, so I stopped.", "앞이 막혀서 멈췄어요.")
return
with _send:
if _stop.is_set():
return
_joy(*cmd)
v = cmd[0]
_stop.wait(TICK_S)
except fetch.Stopped:
pass
except fetch.FetchError as e:
fetch.log(f"follow: {e}")
fetch._say(say, e.args[0], e.args[1] if len(e.args) > 1 else "죄송해요, 따라갈 수 없어요.")
except (ConnectionError, OSError) as e:
fetch.log(f"follow: base error {e}")
fetch._say(say, "Sorry, I can't drive right now.", "죄송해요, 지금은 이동할 수 없어요.")
except Exception as e: # never die silently after "Okay, I'll follow you"
fetch.log(f"follow: failed: {e!r}")
traceback.print_exc()
fetch._say(say, "Sorry, something went wrong, so I stopped following.",
"죄송해요, 문제가 생겨서 따라가기를 멈췄어요.")
finally:
done.set()
with _send:
try:
_joy(0.0, 0.0)
except (ConnectionError, OSError):
pass # one command lasts 0.5 s: the base stops anyway
head.owners = ()
fetch.log("follow: ended")
def start(see, say=None, people=None):
"""Follow the person `see()` reports, in the background; a follow running already is ended first. Call ready()
before saying yes."""
global _thread
if running():
stop()
_thread.join(JOIN_S)
_stop.clear()
fetch.log("follow: start")
_thread = threading.Thread(target=_run, args=(see, say, people), daemon=True, name="follow")
_thread.start()
+160
View File
@@ -0,0 +1,160 @@
"""Head moves copied from a person: record how someone moves their head in front of the head camera, play it back
with Lumi's head.
python tasks/mimic.py record nod 10 # 10 s; look straight at the camera for the first second
python tasks/mimic.py show nod # the recorded angles, nothing moves
python tasks/mimic.py play nod # Lumi's head does it (moves the head)
The person's head turn and nod come from the face keypoints of the pose net (nose against the ears / eyes), relative
to the first second (looking straight). Only yaw and pitch: Lumi's head has no roll. As in a mirror: the person turns
to their left, Lumi turns to its right. The body API's moveto blocks and the head turns ~40 deg/s, so the playback
goes from one recorded pose to the one due when the last move ended: fast shakes come out smaller and slower.
"""
import json
import os
import sys
import time
from pathlib import Path
import cv2
import numpy as np
from robot import head
from vision import camview, pose
ROOT = Path(__file__).resolve().parents[1]
MOVES = ROOT / "data" / "head_moves"
CAMERA = "head"
NEUTRAL_S = (0.3, 1.5) # s of the recording the person looks straight (the zero); the first 0.3 s they settle
YAW_GAIN = 2.0 # Lumi's yaw per degree of the face turn read from the eyes (it reads low); estimate,
# tune live
PITCH_GAIN = 140.0 # deg per unit of nose height change / eye distance; estimate, tune live
MIRROR = True # the person's left = Lumi's right, as in a mirror
SMOOTH = 3 # samples in the running median (15 fps camera)
YAW_MAX = head.YAW_LIMIT # deg
PITCH_ZERO = 12.0 # deg, Lumi's pitch for the person's straight look (room to look down to -5)
MIN_MOVE = 2.0 # deg; smaller changes are not sent
CROSS = 0.5 # a move along one axis gets this much of its size on the other axis, the side
# alternating: diagonal moves, never one axis alone (owner)
VEL = 70 # speed ratio %; the head is at full speed from ~50
def _face(kp):
"""(turn deg, nod) of a face, or None. The turn comes from where the nose sits between the eyes (ears drop out
in a side view, which made the old ear-based turn jump); the nod is the nose height under the eyes over the eye
distance, the eye distance corrected for the turn."""
nose = pose.seen(kp, "nose")
ley, rey = pose.seen(kp, "left_eye"), pose.seen(kp, "right_eye")
if nose is None or ley is None or rey is None:
return None
dl, dr = abs(nose[0] - ley[0]), abs(nose[0] - rey[0])
if dl + dr < 4:
return None
r = float(np.clip((dr - dl) / (dl + dr), -0.99, 0.99)) # + : the nose toward the image's right
eyes = abs(ley[0] - rey[0]) / np.sqrt(1 - r * r) or 1.0
return np.degrees(np.arcsin(r)), ((ley[1] + rey[1]) / 2 - nose[1]) / eyes
def record(name, seconds):
"""Samples [t s, yaw deg, pitch deg] of the biggest face for `seconds`, saved to data/head_moves/<name>.json."""
path, last, raw = camview.raw_path(CAMERA), 0.0, []
start = time.time()
while time.time() - start < seconds:
m = os.stat(path).st_mtime
if m == last:
time.sleep(0.01)
continue
last = m
img = cv2.imread(str(path))
people = pose.detect(img) if img is not None else []
f = _face(people[0]["kp"]) if people else None
if f:
raw.append((time.time() - start, *f))
if len(raw) < 10:
raise SystemExit(f"saw a face in {len(raw)} frames only: stand in front of the head camera")
out = _samples(raw)
MOVES.mkdir(exist_ok=True)
(MOVES / f"{name}.json").write_text(json.dumps({"samples": out, "raw": [[round(float(x), 4) for x in r] for r in raw]}))
return out
def _samples(raw):
"""[t s, yaw deg, pitch deg] for Lumi from the face readings [t, turn deg, nod], relative to the straight look."""
zero = [s for s in raw if NEUTRAL_S[0] <= s[0] < NEUTRAL_S[1]] or raw[:10]
t0, n0 = np.median([s[1] for s in zero]), np.median([s[2] for s in zero])
side = -1 if MIRROR else 1
out = []
for i in range(len(raw)):
w = raw[max(0, i - SMOOTH + 1):i + 1]
turn, nod = np.median([s[1] for s in w]), np.median([s[2] for s in w])
out.append([round(raw[i][0], 2), round(float(np.clip(side * (turn - t0) * YAW_GAIN, -YAW_MAX, YAW_MAX)), 1),
round(float(np.clip(PITCH_ZERO + (nod - n0) * PITCH_GAIN, *head.PITCH_RANGE)), 1)])
return out
def load(name):
d = json.loads((MOVES / f"{name}.json").read_text())
return _samples(d["raw"]) if d.get("raw") else d["samples"] # the raw readings: today's gains
def _diagonal(cur, y, p, side):
"""The pose (y, p) moved so the step from cur changes both axes: the smaller one gets at least CROSS of the bigger,
to `side` (+1 / -1), kept inside the limits."""
dy, dp = y - cur[0], p - cur[1]
if abs(dp) < CROSS * abs(dy):
p = cur[1] + side * CROSS * abs(dy)
if not head.PITCH_RANGE[0] <= p <= head.PITCH_RANGE[1]:
p = cur[1] - side * CROSS * abs(dy)
elif abs(dy) < CROSS * abs(dp):
y = cur[0] + side * CROSS * abs(dp)
return float(np.clip(y, -YAW_MAX, YAW_MAX)), float(np.clip(p, *head.PITCH_RANGE))
def plan(samples, move_s):
"""The poses to send: from each move's end, the pose due then. move_s(dyaw, dpitch) = s a move takes."""
out, t, cur, i = [], 0.0, (0.0, PITCH_ZERO), 0
rec = cur # the recorded pose last sent (cur is it made diagonal)
while i < len(samples):
while i + 1 < len(samples) and samples[i + 1][0] <= t:
i += 1
_, y, p = samples[i]
if max(abs(y - rec[0]), abs(p - rec[1])) >= MIN_MOVE:
rec = (y, p)
y, p = _diagonal(cur, y, p, len(out) % 2 * 2 - 1)
out.append((t, y, p))
t += move_s(y - cur[0], p - cur[1])
cur = (y, p)
elif i + 1 < len(samples):
t = samples[i + 1][0]
else:
break
return out
def play(name, head_api=head):
from audio import sing
lift, waist, _, _ = head_api.status()
start = time.time()
try:
for due, y, p in plan(load(name), lambda dy, dp: sing.move_time(dy, dp, VEL)):
wait = due - (time.time() - start)
if wait > 0:
time.sleep(wait)
head_api.moveto([lift, waist, y, p], VEL, VEL) # blocks: never two moves at once
finally:
head_api.moveto([lift, waist, 0.0, 0.0], VEL, VEL)
if __name__ == "__main__":
what, name = sys.argv[1], sys.argv[2]
if what == "record":
secs = float(sys.argv[3]) if len(sys.argv) > 3 else 10.0
print("look straight at the head camera... go")
s = record(name, secs)
print(f"{len(s)} samples, yaw {min(x[1] for x in s)}..{max(x[1] for x in s)}, "
f"pitch {min(x[2] for x in s)}..{max(x[2] for x in s)}")
elif what == "show":
for s in load(name):
print(*s)
elif what == "play":
play(name)
View File
+397
View File
@@ -0,0 +1,397 @@
"""Generated commands and questions, English, Korean and mixed, with the route Lumi must take: templates x slot
fills (tests/command_check.py runs them).
A case: {"intent", "text", "lang", "state": "idle" | "holding", "before": (text, action line) or None, "expect"}.
expect: alternatives split by " | ":
action:<a> [words] a quick command or the LLM's action (words must be in its target): pick cup, look me
receive [object] take something from the person's hand (the camera checks first)
give | place [thing] hand over / put down what is held
empty_hand nothing is held: "I'm not holding anything"
refuse a fixed refusal ("I won't open my hand while holding something")
mission | status | stop | end | sing | search | weather | ask (a clarifying question) | talk (answer only)
Every case is right, a miss (no motion: talk / ask / unclear where a motion was wanted) or wrong (a motion that was
not asked for, or the wrong one). Nothing may be wrong.
"""
import random
import re
R = random.Random(7) # the same cases every run
OBJ_EN = [("cup", "cup"), ("bottle", "bottle"), ("apple", "apple"), ("banana", "banana"), ("orange", "orange"),
("mug", "cup"), ("red cup", "red cup"), ("white cup", "white cup"), ("blue bottle", "blue bottle"),
("glass", "cup")]
OBJ_KO = [("컵", "cup"), ("병", "bottle"), ("사과", "apple"), ("바나나", "banana"), ("빨간 컵", "red cup"),
("흰 컵", "white cup"), ("파란 병", "blue bottle"), ("오렌지", "orange")]
PRE_EN = ["", "please ", "Lumi, ", "hey Lumi, ", "okay Lumi, ", "um, ", "could you ", "can you ", "would you ",
"uh, could you please ", "Lumi, can you ", "so, ", "alright, "]
PRE_CALL = ["", "Lumi, ", "hey Lumi, ", "okay Lumi, ", "um, ", "so, ", "alright, "] # before a question or "I ..."
POST_EN = ["", " please", " for me", ", thanks", " now", ".", "!", " real quick", " if you can"]
PRE_KO = ["", "루미야 ", "루미야, ", "저기 ", "음 ", "자, ", "혹시 "]
CASES = []
def add(intent, text, expect, lang=None, state="idle", before=None):
lang = lang or ("ko" if any("가" <= ch <= "힣" for ch in text) else "en")
CASES.append({"intent": intent, "text": text, "lang": lang, "state": state, "before": before, "expect": expect})
VARIANTS = 3 # wordings (prefix / suffix) made of each template and fill
def en(intent, templates, expect, slots=None, state="idle", n=VARIANTS):
"""English: every template x slot, n times with a random prefix / suffix (the plain wording first)."""
for tpl in templates:
for word, val in (slots or [("", "")]):
seen = set()
for i in range(n):
asking = re.match(r"(?:what|how|why|where|when|which|who|do|does|is|are|can|could|i\b|i'|my|there|here|"
r"you|nice|hello)", tpl, re.I)
p, s = ("", "") if i == 0 else (R.choice(PRE_CALL if asking else PRE_EN),
"" if asking or tpl.endswith("?") else R.choice(POST_EN))
if p.rstrip().endswith("you") and s in (".", "!"):
s = "?"
text = p + tpl.format(o=word) + s
text = text[0].upper() + text[1:] if i else text
if text not in seen:
seen.add(text)
add(intent, text, expect.format(o=val), state=state)
def ko(intent, templates, expect, slots=None, state="idle", n=VARIANTS):
for tpl in templates:
for word, val in (slots or [("", "")]):
for text in dict.fromkeys(("" if i == 0 else R.choice(PRE_KO)) + tpl.format(o=word) for i in range(n)):
add(intent, text, expect.format(o=val), state=state)
def both(intent, templates, expect, slots=None, state="idle"):
"""English and Korean templates in one list."""
for tpl in templates:
(ko if any("가" <= ch <= "힣" for ch in tpl) else en)(intent, [tpl], expect, slots, state)
# ---------- pick from the table in front ----------
en("pick", ["pick up the {o}", "grab the {o}", "take the {o}", "get the {o}", "pick the {o} up", "lift the {o}",
"pick up that {o}", "grab that {o} on the table", "pick up the {o} in front of you", "take the {o} off the table"],
"action:pick {o} | mission", OBJ_EN)
ko("pick", ["{o} 집어", "{o} 좀 집어 줘", "{o} 잡아", "{o} 들어 봐", "{o} 집어 주세요", "{o}을 들어 줄래?", "테이블에 있는 {o} 집어",
"{o} 좀 잡아 볼래요?"], "action:pick {o} | mission", OBJ_KO)
# pass me X: pick it, then hand it over
en("pass_me", ["pass me the {o}", "hand me the {o}", "give me the {o}", "can I have the {o}", "could I get the {o}",
"bring me that {o} on the table"],
"mission | action:fetch {o}", OBJ_EN[:7])
ko("pass_me", ["{o} 좀 줘", "{o} 건네 줘", "{o} 좀 주세요", "저한테 {o} 좀 주실래요?", "{o} 나한테 줘"],
"mission | action:fetch {o}", OBJ_KO[:6])
# ---------- receive: take it from the person's hand ----------
REC_EN = ["take this", "here, take this", "take this from me", "take it from my hand", "take this from my hand",
"hold this", "hold this for me", "can you hold this?", "here you go", "here, hold it", "grab this from me",
"take what I'm holding", "I want to give you something", "I have something for you, take it"]
REC_EN_OBJ = ["take the {o} from my hand", "take my {o}", "take this {o} from me", "hold this {o}", "I'll give you this {o}",
"here's the {o}, take it", "I want to give you a {o}", "take the {o} I'm holding", "I'm handing you the {o}",
"can you take the {o} from me?", "please hold my {o} for a moment"]
REC_KO = ["이거 받아", "이거 받아 줘", "이거 좀 받아 주세요", "받아", "자, 받아", "받으세요", "드릴게요", "이거 드릴게요", "이거 가져가",
"내 손에 있는 거 가져가", "제 손에 있는 거 가져가세요", "이거 좀 들고 있어", "이거 들고 있어 줄래요?", "이거 줄게"]
REC_KO_OBJ = ["{o} 받아", "{o} 드릴게요", "이 {o} 받아 줘", "제 손에 있는 {o} 가져가세요", "이 {o} 좀 들고 있어", "{o} 받아 줄래요?",
"내가 {o} 줄게", "제가 {o} 드릴게요, 받아 주세요"]
OBJ_ONLY = [(w, v.split()[-1]) for w, v in OBJ_EN[:6]]
OBJ_ONLY_KO = [(w, v.split()[-1]) for w, v in OBJ_KO[:5]]
both("receive", REC_EN + REC_KO, "receive")
en("receive", REC_EN_OBJ, "receive {o}", OBJ_ONLY)
ko("receive", REC_KO_OBJ, "receive {o}", OBJ_ONLY_KO)
both("receive", REC_EN + REC_KO[:6], "receive | refuse", state="holding")
en("receive", REC_EN_OBJ, "receive | refuse", OBJ_ONLY[:3], state="holding")
# ---------- give / place what is held ----------
GIVE_EN = ["give it to me", "give me that", "hand it over", "hand it to her", "give it to him", "pass it to me",
"give it to that person", "can I have it?", "I'll take it", "let me have it", "give it back", "hand it to me",
"give that to my friend", "pass it over here", "give it to the lady", "okay, give it", "hand it to them"]
GIVE_KO = ["줘", "이리 줘", "그거 줘", "나 줘", "저 줘요", "저 사람한테 줘", "그 사람한테 건네 줘", "이 분께 드려", "그거 저한테 주세요",
"이제 줘", "그거 이리 주세요", "그거 내 친구한테 줘", "건네 줘", "저 분한테 드려요"]
PLACE_EN = ["put it down", "put it here", "put it there", "set it down", "leave it here", "put it on the table",
"put it on that table", "place it on the desk", "drop it here", "put it next to the laptop",
"set it down over there", "just put it down", "put that on the table please", "place it here"]
PLACE_KO = ["여기 놔", "거기 놔", "내려놔", "내려 놓아 줘", "테이블에 놔", "책상 위에 올려놔", "여기 둬", "탁자에 놓아 주세요",
"그거 내려놔", "여기에 내려 주세요", "거기 둬", "테이블 위에 놔 줘"]
both("give", GIVE_EN + GIVE_KO, "give", state="holding")
both("give", GIVE_EN + GIVE_KO, "empty_hand | ask | talk")
both("place", PLACE_EN + PLACE_KO, "place | action:put down", state="holding")
both("place", PLACE_EN + PLACE_KO, "empty_hand | ask | talk")
en("give", ["give me the {o}", "hand me the {o}", "can I have the {o}?"], "give", OBJ_ONLY[:5], state="holding")
ko("give", ["{o} 줘", "{o} 이리 주세요"], "give", OBJ_ONLY_KO[:4], state="holding")
en("place", ["put the {o} on the table", "put the {o} down"], "place | action:put down", OBJ_ONLY[:5], state="holding")
both("place", ["put it back", "put it back where it was", "제자리에 놔", "다시 제자리에 둬"], "action:put back", state="holding")
# ---------- the hand: open / close ----------
for t in ["open your hand", "open your gripper", "open your fingers", "let go", "now open it", "open your hand please",
"손 펴", "손 벌려", "손 좀 펴 봐", "손 펴 줘", "손을 열어", "다시 손 펴", "hand open 해 줘", "손 open 해"]:
both("hand", [t], "action:arm open")
both("hand", [t], "refuse | place | give", state="holding") # it would fall
for t in ["close your hand", "now close it", "close it again", "close your fingers", "close your gripper", "make a fist",
"손 쥐어", "주먹 쥐어", "손 오므려", "다시 손 닫아", "손 쥐어 봐", "손 close 해 줘"]:
both("hand", [t], "action:arm close")
# ---------- arm ----------
for t in ["reach out your hand", "stretch out your arm", "put your arm out", "hold out your hand", "extend your arm",
"팔 뻗어", "팔 좀 내밀어 봐", "팔을 쭉 뻗어 줘"]:
both("arm", [t], "action:arm reach")
for t in ["fold your arm", "put your arm down", "tuck your arm in", "put your arm away", "팔 접어", "팔 내려", "팔 거둬"]:
both("arm", [t], "action:arm fold")
# ---------- look ----------
for t, want in [("look at me", "me"), ("look at me please", "me"), ("eyes on me", "me"), ("face me", "me"),
("look over here", "me | center"), ("나 봐", "me"), ("저 좀 봐 주세요", "me"), ("나를 봐", "me"),
("look left", "left"), ("look to your right", "right"), ("look up", "up"), ("look down", "down"),
("look up a bit", "up small"), ("look straight ahead", "center"), ("왼쪽 봐", "left"), ("오른쪽 좀 봐", "right"),
("위를 봐", "up"), ("아래 봐", "down"), ("고개 들어", "up"), ("고개 숙여", "down"), ("정면 봐", "center"),
("turn your head to the left", "left"), ("고개 오른쪽으로 돌려", "right"), ("look behind you", "left"),
("look away", "away"), ("don't look at me", "away"), ("stop looking at me", "away"),
("stop staring at me", "away"), ("please don't stare at me", "away"), ("쳐다보지 마", "away"),
("날 보지 마", "away"), ("나 보지 마세요", "away"), ("다른 데 봐", "away"), ("저 쳐다보지 마세요", "away"),
("look somewhere else", "away"), ("고개 돌려", "away | left | right | center | talk"),
("look at the back side", "left 180"), ("look at back side", "left 180"), ("look at behind", "left 180"),
("look at behind side", "left 180"), ("look at the backside", "left 180"), ("look back", "left 180"),
("look at the big side", "left 180"), ("turn your head back", "left 180"), ("turn around and look", "left 180"),
("look over your right shoulder", "right 180"), ("뒤 봐", "left 180"), ("뒤를 봐", "left 180"),
("뒤돌아 봐", "left 180"), ("뒤쪽 봐", "left 180"), ("뒤에 봐 줘", "left 180"), ("고개 뒤로 돌려", "left 180"),
("오른쪽 뒤 봐", "right 180"), ("back side 봐", "left 180"), ("뒤 좀 look 해 줘", "left 180"),
("look forward", "center"), ("look ahead", "center")]:
alts = " | ".join("talk" if w.strip() == "talk" else f"action:look {w.strip()}" for w in want.split("|"))
both("look", [t], alts)
# ---------- base ----------
for t, want in [("move forward one metre", "action:move forward"), ("go back a little", "action:move back"),
("back up please", "action:move back"), ("step back", "action:move back"), ("scoot forward", "action:move forward"),
("move left 2 meters", "action:move left"), ("앞으로 1미터 가", "action:move forward"),
("뒤로 조금 가 줘", "action:move back"), ("뒤로 물러나", "action:move back"), ("왼쪽으로 50센티 가", "action:move left"),
("turn around", "action:turn around"), ("turn left", "action:turn left"), ("turn right 45 degrees", "action:turn right"),
("spin around", "action:turn around"), ("한 바퀴 돌아", "action:turn around"), ("왼쪽으로 돌아", "action:turn left"),
("come here", "action:come"), ("come to me", "action:come"), ("come closer", "action:come"), ("이리 와", "action:come"),
("여기로 와 줘", "action:come"), ("come over here please", "action:come"),
("go to p3", "action:go_to p3"), ("go to point two", "action:go_to p2"), ("p5로 가", "action:go_to p5"),
("go home", "action:go_to home"), ("go charge yourself", "action:go_to home"), ("충전하러 가", "action:go_to home"),
("can you move?", "action:move back"), ("비켜 줄래요?", "action:move back"), ("get out of the way", "action:move back"),
("move forward ten meters", "talk | refuse"), ("앞으로 10미터 가", "talk | refuse"), ("go to the kitchen", "talk | ask"),
("go to p77", "talk | ask"), ("주방으로 가", "talk | ask"),
("let's back 1 meter", "action:move back 1"), ("lets back 1 meter", "action:move back 1"), # 2026-10-21:
("Let's bake one meter.", "action:move back 1"), ("Big one meter.", "action:move back 1"), # whisper's
("Let's bake one metal.", "action:move back 1"), ("go back 1 meter", "action:move back 1"), # slips
("move back one metre", "action:move back 1"), ("back up 2 meters", "action:move back 2"),
("reverse half a meter", "action:move back 0.5"), ("go backwards one meter", "action:move back 1"),
("1미터 뒤로 가", "action:move back 1"), ("뒤로 2미터 가 줘", "action:move back 2"),
("1미터 후진해", "action:move back 1"), ("I'm stuck, go back one meter", "action:move back 1"),
("come back p9", "action:go_to p9"), ("come back here", "action:come")]:
both("base", [t], want)
# ---------- body ----------
for t, want in [("raise yourself", "action:lift up"), ("get taller", "action:lift up"), ("lower yourself a bit", "action:lift down"),
("키 좀 높여", "action:lift up"), ("키 낮춰 줘", "action:lift down"), ("wave", "action:wave"),
("wave at me", "action:wave"), ("can you wave?", "action:wave"), ("손 흔들어 줘", "action:wave"),
("손 인사 해 봐", "action:wave"), ("wave goodbye to my friend", "action:wave"), ("be quiet", "action:quiet"),
("조용히 해", "action:quiet"), ("stop", "stop"), ("stop!", "stop"), ("freeze", "stop"), ("멈춰", "stop"),
("그만", "stop"), ("don't move", "stop"), ("움직이지 마", "stop")]:
both("body", [t], want)
# ---------- fetch / missions ----------
for word, val in OBJ_EN[:5]:
add("fetch", f"bring me the {word} from p2", f"action:fetch {val} | mission")
add("fetch", f"go to p3 and get the {word}", f"action:fetch {val} | mission")
add("fetch", f"could you fetch the {word} from point one for me?", f"action:fetch {val} | mission")
for word, val in OBJ_KO[:5]:
add("fetch", f"p2에서 {word} 가져와", f"action:fetch {val} | mission")
add("fetch", f"{word} 들고 p3로 가서 테이블에 놔", f"mission | action:fetch {val}")
for t in ["take the cup, go to p3 and give it to Mina", "pick up the bottle, turn around and give it to me",
"go to p2, wait 10 seconds and come back", "컵 집어서 p3로 가서 줘", "pick up the apple and hand it to me",
"take the cup and put it on the chair", "사과 집어서 나한테 줘"]:
add("mission", t, "mission | action:fetch")
# ---------- status ----------
for t in ["what are you holding?", "what's in your hand?", "where are you going?", "what are you doing?", "뭐 하고 있어?",
"손에 뭐 있어?", "뭐 들고 있어?", "are you holding something?", "is your hand empty?", "어디 가?", "지금 바빠?",
"what are you up to?", "what have you got there?", "뭐 하는 중이에요?", "그거 뭐야, 손에 든 거?"]:
both("status", [t], "status")
both("status", [t], "status", state="holding")
# ---------- what the cameras see (assistant/seeing.py answers) ----------
for t in ["do you see a cup?", "can you see the red cup?", "is there an apple on the table?", "how far is the cup?",
"what do you see?", "what's in front of you?", "how many people are there?", "can you see me?",
"what am I holding?", "what's in my hand?", "is my hand raised?", "what am I pointing at?", "what am I doing?",
"what color is my shirt?", "am I wearing glasses?", "how far am I from you?", "컵 보여?", "앞에 뭐가 있어?",
"몇 명 보여?", "내가 뭐 들고 있어?", "내 손에 뭐 있어?", "나 보여?", "내가 뭘 가리키고 있어?", "사과 보여요?",
"뒤에 누가 있어?", "내가 지금 뭐 하고 있어?", "what's behind you?", "뒤에 뭐 있어?", "who is behind you?"]:
both("seeing", [t], "seeing")
for t in ["what are you holding?", "what's in your hand?", "손에 뭐 들고 있어?"]: # Lumi's own hand: the task state
both("seeing", [t], "status")
for t in ["How many people work at Cutshion company?", "how many people work at cutshion campy?", # 2026-10-21: the
"how many employees does Cutshion have?", "how many people work there?", "직원이 몇 명이에요?", # company, from
"쿳션에는 몇 명이 일해요?"]: # knowledge
both("question", [t], "talk")
for t in ["I'll be back", "I'm behind you", "I'll be right back"]: # "back", "behind": no head turn
both("question", [t], "talk | end")
# ---------- things it can't do: a plain answer, no motion ----------
for t in ["can you fly?", "jump", "jump for me!", "dance for me", "can you dance?", "climb the stairs", "open the door",
"make me a coffee", "lift this table", "pick up that chair", "go upstairs", "do a backflip", "run!", "sit down",
"날아 봐", "점프해", "춤 춰 줘", "커피 타 줘", "계단 올라가", "문 열어 줘", "이 책상 들어 봐", "앉아", "pick up my phone",
"take my laptop", "carry me", "give me a hug", "shake hands with me", "throw the cup", "kick the ball",
"pick me up", "날 안아 줘", "공 차 봐", "이 의자 옮겨 줘", "pick up the box", "bring me a pizza"]:
both("cannot", [t], "talk | ask | unclear")
# ---------- questions, not orders ----------
for t in ["can you pick up a bottle?", "how do you open your hand?", "do you know how to wave?",
"what happens if I put something in your hand?", "손 펼 수 있어요?", "how much can you lift?",
"can you hold a cup?", "how do you know where the cup is?", "why do you look at me?", "can you turn your head?",
"컵 집을 수 있어요?", "어떻게 물건을 잡아요?", "is it hard to pick up a cup?", "can you give things to people?",
"do you take things from people's hands?", "what can you carry?", "how far can you move?", "can you see me?"]:
both("question", [t], "talk | status | seeing")
# ---------- tricks: things that may not be there (the route is right; lumi checks with the camera) ----------
for t, want in [("take the apple from my hand", "receive apple"), ("take the banana I'm holding", "receive banana"),
("내 손에 있는 사과 가져가", "receive apple"), ("I'm giving you a bottle, take it", "receive bottle"),
("give me the apple you are holding", "give | empty_hand | ask | talk"),
("put the banana you're holding on the table", "place | empty_hand | ask | talk")]:
add("trick", t, want)
# ---------- corrections after an action ----------
for t in ["no, the other one", "not that one", "no, not that", "아니 그거 말고", "그거 말고 다른 거", "wrong one", "no no no, the other cup",
"아니, 그거 아니야"]:
add("correction", t, "ask | stop | talk", before=("pick up the cup", "ACTION: pick cup"))
for t, want in [("no, the red one", "action:pick red | ask"), ("아니, 빨간 거", "action:pick red | ask"),
("no, the bottle", "action:pick bottle | ask"), ("not the cup, the apple", "action:pick apple | ask")]:
add("correction", t, want, before=("pick up the cup", "ACTION: pick cup"))
for t, want in [("now close it", "action:arm close"), ("and the other way", "action:look right | ask | talk"),
("a bit more", "action:look left | ask | talk")]:
add("follow_up", t, want, before=("look left" if "way" in t or "more" in t else "open your hand",
"ACTION: look left" if "way" in t or "more" in t else "ACTION: arm open"))
# ---------- mixed English / Korean ----------
for t, want in [("cup 좀 pick up 해 줘", "action:pick cup | mission"), ("look at me 해 봐", "action:look me"),
("이거 take 해", "receive"), ("bottle 줘", "mission | action:fetch bottle"), ("left 봐", "action:look left"),
("wave 해 줘", "action:wave"), ("p3로 go", "action:go_to p3"), ("손 close 해", "action:arm close"),
("apple 집어 줘", "action:pick apple | mission"), ("come here 해", "action:come"),
("이거 hold 해 줘", "receive"), ("put it down 해 줘", "empty_hand | ask | talk")]:
add("mixed", t, want)
# ---------- speech recognition slips ----------
for t, want in [("pick up the cop", "talk | ask | unclear"), ("grab the cap", "talk | ask | unclear"),
("Lumi luck at me", "action:look me | talk | ask | unclear"), ("give it too me", "empty_hand | talk | ask"),
("put it hear", "empty_hand | talk | ask"), ("loomi come hear", "action:come | talk | ask | unclear"),
("pic up the cup", "action:pick cup | talk | ask | unclear"), ("the cup the cup", "talk | ask | unclear"),
("컵 집어 줘 어", "action:pick cup | mission"), ("루미야 이리와", "action:come"), ("손펴", "action:arm open"),
("고개들어", "action:look up"), ("p 3으로 가", "action:go_to p3 | talk | ask"),
("uh take the uh the cup", "action:pick cup | mission | ask"), ("move four word", "talk | ask | unclear")]:
add("asr", t, want)
# ---------- long, rambling ----------
for t, want in [("okay so um I was wondering if maybe you could, like, pick up the red cup for me, if that's okay",
"action:pick red cup | mission"),
("so I'm holding this apple and I'd like you to take it from me", "receive apple"),
("you know what, I think it would be really nice if you could look at me while we talk", "action:look me"),
("hey Lumi, sorry to bother you, but could you please move back a little bit, you're kind of in the way",
"action:move back"),
("루미야 내가 지금 손에 컵을 들고 있는데 이거 좀 받아 줄래", "receive cup"),
("음 그러니까 저기 테이블 위에 있는 빨간 컵 있잖아 그거 좀 집어 줄 수 있어", "action:pick red cup | mission"),
("I don't really need it anymore so could you just put it down somewhere", "place | action:put down"),
("Lumi, when you get a second, could you hand that to my colleague over there", "give")]:
add("ramble", t, want, state="holding" if ("put it down somewhere" in t or "hand that" in t) else "idle")
# ---------- chat that is not a command ----------
for t in ["hello", "how are you?", "what's your name?", "nice to meet you", "you're cute", "who made you?", "안녕하세요",
"이름이 뭐예요?", "몇 살이에요?", "I like your hand", "your arm looks strong", "is that your hand?",
"I have an apple", "I'm holding a cup", "there's a cup on the table",
"저 사람은 내 친구야", "사과 좋아해?", "I gave my friend a cup yesterday", "look, it's raining"]:
both("chat", [t], "talk | status")
both("chat", ["my friend is over there"], "talk | action:look") # looking that way is fine
# ---------- distances and speed by voice (assistant/driving.py): exact amounts, vague ones, "again", limits ----------
MOVED = ("go back 20 cm", "ACTION: move back 0.2")
SPED = ("a bit faster", "ACTION: speed 1\nOkay, a bit faster: 120 percent of my normal speed.")
SLOWED = ("천천히", "ACTION: speed -1\n네, 조금 더 천천히 갈게요. 보통 속도의 80퍼센트예요.")
TALKED = ("what's your name?", "ACTION: none -\nI'm Lumi.")
for t, want, before in [
# exact: digits, words, units, Korean, whisper's slips ("come back to" for "come back", "bake", "metal")
("Let's come back to 20 cm.", "action:move back 0.2", None), ("come back 20 cm", "action:move back 0.2", None),
("go forward 30 cm", "action:move forward 0.3", None), ("move back 5 centimeters", "action:move back 0.05", None),
("move back fifteen centimetres please", "action:move back 0.15", None),
("could you back up two hundred millimetres", "action:move back 0.2", None),
("move forward one point five meters", "action:move forward 1.5", None),
("go back 1 cm", "action:move back 0.01", None), ("move back 10 mm", "action:move back 0.01", None),
("Let's bake 20 cm.", "action:move back 0.2", None), ("big 30 centimeters", "action:move back 0.3", None),
("go back 2 metals", "action:move back 2", None), ("move left 40 cm", "action:move left 0.4", None),
("20센티 뒤로", "action:move back 0.2", None), ("20센티 뒤로 가 줘", "action:move back 0.2", None),
("앞으로 반 미터", "action:move forward 0.5", None), ("앞으로 반 미터 가", "action:move forward 0.5", None),
("이십 센티 뒤로 가", "action:move back 0.2", None), ("일 미터 앞으로 가", "action:move forward 1", None),
("뒤로 오십 센치만 가 줘", "action:move back 0.5", None), ("루미야 뒤로 삼십 센티 가", "action:move back 0.3", None),
("뒤로 10 cm 가", "action:move back 0.1", None), ("back 20센티", "action:move back 0.2", None),
# vague: a fixed estimate, read back with "about"
("back up a tiny bit", "action:move back 0.05", None), ("a hair to the left", "action:move left 0.05", None),
("inch forward", "action:move forward 0.05", None), ("scoot back just a touch", "action:move back 0.05", None),
("살짝 뒤로", "action:move back 0.05", None), ("살짝만 앞으로 가 줘", "action:move forward 0.05", None),
("한 뼘 앞으로", "action:move forward 0.2", None), ("반 걸음 뒤로", "action:move back 0.25", None),
("한 걸음 뒤로 가", "action:move back 0.5", None), ("two steps back", "action:move back 1", None),
("take a step forward", "action:move forward 0.5", None), ("go back a little", "action:move back 0.5", None),
# not understood or too far: asked / refused with the limit, never a default
("move back 20", "ask", None), ("go back a couple of meters", "ask", None), ("move back a few steps", "ask", None),
("move forward 2 feet", "ask", None),
("move back 5 meters", "refuse", None), ("go forward 2 km", "refuse", None), ("drive back three miles", "refuse", None),
("뒤로 5미터 가", "refuse", None), ("앞으로 천 미터 가", "refuse", None), ("move back 1 mm", "refuse", None),
# places and other things stay what they are
("come back here", "action:come", None), ("come back to p9", "action:go_to p9", None),
("come back p9", "action:go_to p9", None), ("go right ahead", "talk", None), ("look left a bit", "action:look left", None),
("I live a few metres to the left", "talk", None), ("I'll be right back", "talk | end", None),
# speed
("go a bit faster", "speed faster", None), ("faster", "speed faster", None), ("speed up", "speed faster", None),
("a little faster please", "speed faster", None), ("can you pick up the pace", "speed faster", None),
("even faster", "speed faster", None), ("way too slow", "speed faster", None), ("hurry up Lumi", "speed faster", None),
("you're too slow", "speed faster", None),
("slower", "speed slower", None), ("slow down", "speed slower", None), ("a bit slower", "speed slower", None),
("too fast", "speed slower", None), ("not so fast", "speed slower", None), ("ease off", "speed slower", None),
("slow it down a notch", "speed slower", None), ("Lumi, slow down please", "speed slower", None),
("빨리", "speed faster", None), ("더 빨리", "speed faster", None), ("좀 더 빨리 가 줘", "speed faster", None),
("너무 느려", "speed faster", None), ("천천히", "speed slower", None), ("더 천천히", "speed slower", None),
("속도 줄여", "speed slower", None), ("너무 빨라", "speed slower", None), ("좀 천천히 가 줄래요", "speed slower", None),
("천천히 가세요", "speed slower", None), ("go slower 좀", "speed slower", None),
# right after a move or a speed change: "more" / "again" repeat it; with nothing before: asked
("again", "action:move back 0.2", MOVED), ("a bit more", "action:move back 0.2", MOVED),
("same again", "action:move back 0.2", MOVED), ("one more time", "action:move back 0.2", MOVED),
("한 번 더", "action:move back 0.2", MOVED), ("조금 더", "action:move back 0.2", MOVED),
("just a few centimetres more", "action:move back 0.05", MOVED), ("10센티 더", "action:move back 0.1", MOVED),
("more", "speed faster", SPED), ("a bit more", "speed faster", SPED), ("again", "speed faster", SPED),
("조금 더", "speed faster", SPED), ("less", "speed slower", SPED), ("한 번 더", "speed slower", SLOWED),
("more", "ask", None), ("한 번 더", "ask", None), ("a bit more", "ask", None),
("more", "talk", TALKED)]:
add("drive", t, want, before=before)
# ---------- slang, short and casual ----------
for t, want, st in [
("yo Lumi, snag that apple", "action:pick apple | mission", "idle"), ("could ya grab the orange real quick", "action:pick orange | mission", "idle"),
("mind passing me the cup?", "mission | action:fetch cup", "idle"), ("lemme have the cup", "mission | action:fetch cup", "idle"),
("gimme that", "give", "holding"), ("gimme that", "empty_hand | talk", "idle"), ("gimme", "give", "holding"),
("get over here", "action:come", "idle"), ("scooch back a bit", "action:move back", "idle"),
("back off a little", "action:move back", "idle"), ("eyes over here", "action:look me | action:look center", "idle"),
("quit staring", "action:look away", "idle"), ("drop that here", "place", "holding"), ("chuck it on the table", "place", "holding"),
("here, catch", "receive", "idle"), ("yours now, take it", "receive", "idle"), ("open up your hand", "action:arm open", "idle"),
("clench your fist", "action:arm close", "idle"), ("hands up!", "talk | action:arm reach | action:lift up", "idle"),
("야 그거 줘 봐", "give", "holding"), ("컵 좀 집어 봐라", "action:pick cup | mission", "idle"), ("이리 와 봐", "action:come", "idle"),
("고개 좀 왼쪽으로 돌려 봐", "action:look left", "idle"), ("손 좀 펴 봐라", "action:arm open", "idle"),
("그거 이리 내놔", "give", "holding"), ("자 받아라", "receive", "idle"), ("이거 맡아 줘", "receive", "idle"),
("그만 쳐다봐", "action:look away", "idle"), ("좀 비켜 봐", "action:move back", "idle"), ("뒤로 좀 빠져", "action:move back", "idle"),
("사과 하나만 줘", "mission | action:fetch apple", "idle"), ("거기다 놔", "place", "holding"), ("바닥에 내려놔", "place | talk", "holding"),
("손 꽉 쥐어", "action:arm close", "idle"), ("팔 쭉 펴", "action:arm reach", "idle"), ("한 바퀴 돌아 봐", "action:turn around", "idle")]:
add("slang", t, want, state=st)
# ---------- near misses: not a hand-over, not a correction ----------
for t, want, st, before in [("I get it", "talk", "idle", None), ("hold that thought", "talk", "idle", None),
("leave it", "talk", "holding", None), ("그냥 둬", "talk", "holding", None),
("no thanks", "talk | end", "idle", ("pick up the cup", "ACTION: pick cup")),
("no worries", "talk | end", "idle", ("pick up the cup", "ACTION: pick cup")),
("I'll take a photo of you", "talk", "idle", None), ("can I take a picture?", "talk", "idle", None),
("take care", "end | talk", "idle", None), ("take your time", "talk", "idle", None),
("here is fine", "talk", "idle", None), ("I'm giving a talk later", "talk", "idle", None),
("give me a second", "talk", "idle", None), ("give me a minute to think", "talk", "idle", None),
("hand on heart, you're great", "talk", "idle", None), ("잠깐만 기다려 줘", "talk | stop", "idle", None),
("받아 적어 줘", "talk", "idle", None), ("놀라지 마", "talk", "idle", None),
("And take things from me?", "talk", "idle", ("can you give things to people?", "ACTION: none -\nYes.")),
("I dropped my pen on the floor. Can you get it?", "talk", "idle", None)]:
add("near_miss", t, want, state=st, before=before)
+199
View File
@@ -0,0 +1,199 @@
"""Generated commands (tests/command_cases.py) through Lumi's routing, per intent: right, missed (no motion) or wrong.
.venv/bin/python tests/command_check.py # rules only; cases the rules leave are "llm?" (not judged)
.venv/bin/python tests/command_check.py --llm # those go to the real LLM (action line + first sentence)
.venv/bin/python tests/command_check.py --cached # the LLM's answers from the last --llm run where the text is
# the same (fast, after a rule change)
.venv/bin/python tests/command_check.py receive # only this intent
-> logs/command_check.md / .json. The order is lumi.answer()'s with nothing running and the hand empty ("idle") or
holding something ("holding"): stop, what the cameras see (seeing.answer), status, the hand (brain.hand_request), mission, goodbye / closing words, song,
keyword rules, then the LLM's action line acted on as lumi.answer() does. Nothing moves; the LLM is only asked.
"""
import collections
import json
import pathlib
import re
import sys
import time
from assistant import brain, driving, lumi, seeing
from audio import sing
from tests.command_cases import CASES
from tests.conversation_check import NOW, markers
ROOT = pathlib.Path(__file__).resolve().parents[1]
OUT = ROOT / "logs" / "command_check"
HOLDING_NOW = "I'm holding a cup and waiting for what to do with it."
NO_MOTION = {"seeing", "talk", "unclear", "status", "empty_hand", "refuse", "search", "weather", "llm?", "ask", "speed"}
QUICK = {"go_to", "come", "quiet", "weather", "search", "move", "turn", "arm", "pick", "put", "move_object", "fetch",
"look", "lift", "wave"} # lumi.quick_command
def seen(text):
"""assistant/seeing.answer() takes these words (its own test: tests/test_seeing.py); the camera is not asked."""
t = text.strip()
if seeing.HOW_MANY.search(t) and seeing.NOT_IN_VIEW.search(t):
return False # "how many people work at Cutshion?"
return not seeing.ORDER.search(t) and any(rx.search(t) for rx in (
seeing.WEARING, seeing.HOLDING, seeing.SHIRT, seeing.RAISED, seeing.POINTING, seeing.DOING, seeing.SEE_ME,
seeing.HOW_MANY, seeing.BEHIND, seeing.HOW_FAR, seeing.SEE_THING, seeing.THERE_IS, seeing.SEE_THING_KO,
seeing.WHAT_SEE))
def rules(text, state, marks, b):
"""The route lumi.answer() takes before the LLM, or None."""
holding = state == "holding"
if lumi.FOREIGN_SCRIPT.search(text):
return "unclear"
t = brain._norm(text) # lumi.drive_words: speed, "again", how far?, too far
drive = driving.read(t, driving.last_command(b.history), driving.talking(b.history))
if drive and (drive[0] != "move" or drive != driving.read(t, None, True)):
return {"speed": lambda d: f"speed {'faster' if d[1] > 0 else 'slower'}", "move": lambda d: f"action:move {d[1]}",
"refuse": lambda d: "refuse", "ask": lambda d: "ask"}[drive[0]](drive)
if lumi.NAME_ONLY.match(text):
return "talk"
if lumi.stop_order(text, marks):
return "stop"
if seen(text):
return "seeing"
if lumi.status_question(text):
return "status"
cor = brain.correction(text, b.history)
if cor:
return "talk" if cor[0] == "ask" else f"action:{cor[0]} {cor[1]}"
hand = brain.hand_request(text, holding, b, marks)
if hand:
return {"receive": lambda h: "receive " + (h[1] or "") if not holding else "refuse",
"give": lambda h: "give" if holding else "empty_hand",
"place": lambda h: "place " + ((h[1] or {}).get("name") or "") if holding else "empty_hand",
"refuse": lambda h: "refuse", "ask": lambda h: "talk"}[hand[0]](hand).strip()
read = lumi.read_mission(text, marks)
if read:
return "talk" if read[1] else "mission"
if lumi.talk_fate(text) == "end":
return "end"
if lumi.talk_fate(text) == "wait":
return "talk"
if sing.asked(text):
return "sing"
rule = brain.intent(text, marks)
if rule and rule[0] in QUICK:
return rule[0] if rule[0] in ("weather", "search") else f"action:{rule[0]} {rule[1]}".strip()
return None
def llm(text, state, marks, b):
"""(route, action line, first sentence) from the real model, acted on like lumi.answer()."""
brain.FORCED_LANG["lang"] = "ko" if brain.HANGUL.search(text) else "en"
gen = b.respond_stream(text, marks, now=HOLDING_NOW if state == "holding" else NOW)
head = next(gen)
first = next(gen, "") or ""
gen.close()
target = (brain._mentions(text, marks).get("object") or "") if head["action"] == "receive" else head["target"]
return act(head["action"], target, first, state), f"{head['action']} {target}".strip(), first
def refused(route):
"""A pick / receive / fetch of a thing the fingers can't take is answered with the reason (skills.refusal)."""
from manipulation import skills
from tasks import fetch
words = route.split(None, 1)
if words[0] in ("action:pick", "action:move_object", "receive") and len(words) > 1 and \
any(skills.refusal(c) for c in set(brain.OBJECTS.values()) if words[1].endswith(c)):
return "refuse"
if words[0] == "action:fetch":
obj = brain.fetch_from_text(words[1])[0].get("object") if len(words) > 1 else None
if obj and skills.refusal(obj):
return "refuse"
return route
def act(a, target, first, state):
if a in ("none", "end"):
return "talk"
if a in ("give", "place", "receive"):
if a == "receive":
return f"receive {target}".strip() if state == "idle" else "refuse"
return a if state == "holding" else "empty_hand"
if a in ("unclear", "search", "weather", "sing", "stop"):
return a
return f"action:{a} {target}".strip()
def ok(expect, got):
"""'right' | 'missed' | 'wrong'."""
g = got.lower().split()
for alt in expect.split(" | "):
want = refused(alt).split() # "pick bottle": the reason why not is right
if want[0] in ("talk", "ask") and g[0] in ("talk", "ask", "refuse"): # a reason why not is an answer
return "right"
if want[0] == "action:fetch" and g[0] == "action:fetch":
return "right" # parse_fetch reads the words later
if want[0] == g[0] and all(w in g[1:] for w in want[1:]):
return "right"
return "missed" if g[0] in NO_MOTION else "wrong"
def main(args):
marks = markers()
use_llm, cached = "--llm" in args, "--cached" in args
only = [a for a in args if not a.startswith("-")]
old = {}
if cached and OUT.with_suffix(".json").exists():
old = {(r["text"], r["state"], str(r["before"])): r for r in json.loads(OUT.with_suffix(".json").read_text())
if r.get("raw")}
rows, t0 = [], time.time()
for i, c in enumerate(c for c in CASES if not only or c["intent"] in only):
b = brain.Brain()
if c["before"]:
b.history.append(tuple(c["before"]))
brain.FORCED_LANG["lang"] = c["lang"] if c["lang"] in ("en", "ko") else "ko"
got, raw, first = rules(c["text"], c["state"], marks, b), "", ""
if got is None:
key = (c["text"], c["state"], str(c["before"]))
if key in old:
raw, first = old[key]["raw"], old[key]["first"]
a, _, tgt = raw.partition(" ")
got = act(a, tgt, first, c["state"])
elif use_llm:
try:
got, raw, first = llm(c["text"], c["state"], marks, b)
except Exception as e: # noqa: BLE001 - a crash is a failure of that case
got, raw = "error", repr(e)
else:
got = "llm?"
got = refused(got) if got not in ("llm?", "error") else got
verdict = ok(c["expect"], got) if got != "llm?" else "llm?"
rows.append({**c, "got": got, "raw": raw, "first": first, "verdict": verdict, "by": "llm" if raw else "rules"})
if verdict == "wrong" or verdict == "missed" and "-v" in sys.argv:
print(f"{i} {verdict.upper():6} [{c['intent']}/{c['state']}] {c['text']!r} -> {got} (want {c['expect']}) "
f"{first[:60]!r}", flush=True)
OUT.with_suffix(".json").write_text(json.dumps(rows, ensure_ascii=False, indent=0))
report(rows, time.time() - t0)
def report(rows, secs):
by = collections.defaultdict(collections.Counter)
for r in rows:
by[r["intent"]][r["verdict"]] += 1
by["ALL"][r["verdict"]] += 1
lines = [f"# Command check ({time.strftime('%Y-%m-%d %H:%M')}, model {brain.MODEL}, {secs:.0f} s)", "",
f"{len(rows)} cases. right / missed (no motion) / wrong (a motion not asked for) / not run (LLM).", "",
"| intent | cases | right | missed | wrong | llm? | by LLM |", "|---|---|---|---|---|---|---|"]
llm_n = collections.Counter(r["intent"] for r in rows if r["by"] == "llm")
for k in sorted(by, key=lambda k: (k == "ALL", k)):
c = by[k]
n = sum(c.values())
lines.append(f"| {k} | {n} | {c['right']} | {c['missed']} | {c['wrong']} | {c['llm?']} | "
f"{llm_n[k] if k != 'ALL' else sum(llm_n.values())} |")
lines += ["", "## Wrong", ""] + [f"- [{r['intent']}/{r['state']}] {r['text']!r} -> {r['got']} (want {r['expect']}) "
f"{r['first'][:80]!r}" for r in rows if r["verdict"] == "wrong"]
lines += ["", "## Missed", ""] + [f"- [{r['intent']}/{r['state']}] {r['text']!r} -> {r['got']} (want {r['expect']}) "
f"{r['first'][:80]!r}" for r in rows if r["verdict"] == "missed"]
OUT.with_suffix(".md").write_text("\n".join(lines) + "\n")
print("\n".join(lines[:len(by) + 6]))
if __name__ == "__main__":
main(sys.argv[1:])
+277
View File
@@ -0,0 +1,277 @@
"""What visitors ask Lumi about Cutshion Company, and what the answer must (not) contain.
CASES = [{"text", "lang", "must", "must_not"}]: case-insensitive regexes on the spoken reply; every must has to
match, no must_not may. Facts come only from knowledge/cutshion_en.md (taken from cutshion.com); where the website
says nothing, must is a "not sure"-like phrase and must_not a made-up value. Checked by tests/company_check.py.
"""
NOT_SURE = (r"not sure|don'?t know|do not know|not known|no information|don'?t have|do not have|isn'?t (on|listed)|"
r"not (on|listed)|not something i (have|know)|staff|contact|ask|모르|몰라|알 수 없|알지 못|확실하지|정보가 없|정보는 없|"
r"없어서|가지고 있지 않|나와 있지 않|직원|문의|연락")
PRICE = r"\$\s*\d|\d[\d,.]*\s*(?:won|원|dollars?|달러|만|억|million|thousand|천)"
COUNT = r"\d+\s*(?:people|persons?|employees|staff|workers|명)"
JAKA = r"jaka|자카|제이카"
CO = r"cutshion|쿳션" # the site writes 쿳션 ((주)쿳션); 컷션 / 커션 are wrong
OFFER = r"more|like to (know|hear)|anything|which|what else|궁금|알려 드릴|소개해 드릴|더 알고"
LONG = r"(?s)^.{350,}" # the short company answer is short
ROBOT = r"robot|로봇"
APP = r"app|application|solution|애플리케이션|앱|솔루션"
SEOUL = r"seoul|서울"
FOUNDED = r"2022"
CEO = r"lee min|min-?seok|이민석"
BARISTA = r"barista|바리스타"
DRAW = r"draw|드로잉|그림|그려"
COFFEE = r"espresso|coffee|에스프레소|커피"
PHOTO = r"photo|picture|camera|selfie|사진|카메라|촬영"
COOK = r"cook|조리|요리"
ICE = r"ice ?cream|아이스크림"
CANDY = r"candy|캔디"
WELD = r"weld|용접"
PALLET = r"pallet|팔레"
EDU = r"educat|school|kit|교육|키트|학교"
PHONE = r"070.?8959.?2960"
EMAIL = r"cutshion@cutshion\.com|cutshion at cutshion"
CASES = []
def add(lang, rows):
"""rows: (text, must[, must_not]); must / must_not: a regex or a list of them."""
for r in rows:
text, must, must_not = (list(r) + [[]])[:3]
CASES.append({"text": text, "lang": lang,
"must": [must] if isinstance(must, str) else list(must),
"must_not": [must_not] if isinstance(must_not, str) else list(must_not)})
# --- facts on the website, English
add("en", [
("What does Cutshion do?", [ROBOT, APP]),
("What kind of company is Cutshion?", [ROBOT, OFFER], LONG),
("Tell me about your company.", [ROBOT, OFFER], LONG),
("What is Cutshion?", [ROBOT, OFFER], LONG),
("What's Cutshion's main business?", [ROBOT]),
("Who made you?", CO, JAKA),
("Which company built you?", CO, JAKA),
("Where is Cutshion?", SEOUL),
("Where is your company located?", SEOUL),
("Where is the head office?", [SEOUL, r"yeongdeungpo|mullae|seonyu"]),
("What's the address of Cutshion?", r"seonyu|mullae|yeongdeungpo"),
("Is Cutshion a Korean company?", r"yes|korea"),
("Which country is Cutshion from?", r"korea"),
("Does Cutshion have an office in America?", r"mclean|virginia|yes"),
("Do you have a branch in Daegu?", r"yes|daegu"),
("Where is the Cutshion factory?", r"mullae|seoul"),
("Where is the research lab?", r"magok|gangseo|seoul"),
("When was Cutshion founded?", FOUNDED),
("How old is Cutshion?", FOUNDED + r"|four|4|three|3"),
("Who is the CEO of Cutshion?", CEO),
("Who founded Cutshion?", CEO),
("Who is the boss of your company?", CEO),
("What robots does Cutshion make?", [BARISTA, DRAW]),
("What products do you have?", [ROBOT]),
("What robot apps does Cutshion have?", [BARISTA]),
("Tell me about the barista robot.", COFFEE),
("What does the barista robot do?", COFFEE),
("Can your company's robot make coffee?", [r"yes|barista", COFFEE]),
("Does the barista robot replace baristas?", r"barista|repeat|together|help"),
("Who uses the barista robot?", r"mega|sonovictus|cafe|coffee"),
("Did Cutshion sell barista robots to America?", [r"200|sonovictus|yes"]),
("Tell me about the drawing robot.", [DRAW, PHOTO]),
("How does the AI drawing robot work?", [PHOTO, DRAW]),
("Can the robot draw my portrait?", DRAW),
("Where is the drawing robot used?", r"event|school|educat|promot"),
("What types of drawing robot are there?", r"kiosk|all-in-one"),
("Tell me about the cooking robot.", COOK),
("What is GOMCOOK?", COOK),
("Does Cutshion have a chicken robot?", r"chicken|chimaek|yes|cook"),
("Tell me about the ice cream robot.", [ICE, r"kiosk|order|touch"]),
("How long does the ice cream robot take?", r"30|thirty"),
("How many cones does the ice cream robot hold?", r"40|forty"),
("What is the candy ball robot?", [CANDY, r"colou?r|pick"]),
("How fast is the candy ball robot?", r"20|twenty"),
("Tell me about the welding robot.", WELD, JAKA),
("What does the palletizing robot do?", PALLET),
("Who did Cutshion make the palletizing robot with?", r"screen"),
("What is the educational robot?", EDU),
("Do you have robots for schools?", EDU),
("What is Pionoid?", r"platform|api"),
("What is CUVision?", r"vision"),
("Does Cutshion do AI vision?", r"vision"),
("Does Cutshion sell robot arms?", r"yes|collaborative|cobot|hardware", JAKA),
("Does Cutshion sell logistics robots?", r"tusk|yes|logistic"),
("Does Cutshion sell industrial robots?", r"peitian|yes|industrial"),
("What design software does Cutshion offer?", r"solidworks"),
("What is Cutshion's slogan?", r"soft.{0,5}flexible"),
("What is Cutshion's mission?", r"application|app"),
("What awards has Cutshion won?", r"roboworld|robo world|vivatech|viva ?tech"),
("Did Cutshion go to CES?", r"yes|ces"),
("Who are Cutshion's partners?", r"omron|zimmer|screen|daesung|borgwarner"),
("Has Cutshion received investment?", r"seed|500|cnt|evergreen|yes"),
("How can I contact Cutshion?", [r"phone|email|website|070|cutshion\.com|cutshion@"]),
("What's Cutshion's phone number?", PHONE),
("What's the email of your company?", EMAIL),
("What's Cutshion's website?", r"cutshion\.com|cutshion dot com"),
("I want to buy a robot. Who do I talk to?", r"contact|staff|070|email|cutshion\.com|website", PRICE),
("Can I buy a barista robot?", r"contact|staff|070|email|website|yes|cutshion", PRICE),
("Does Cutshion have a YouTube channel?", r"yes|youtube"),
("Is Cutshion a startup?", r"2022|yes|venture|startup|young"),
])
# --- not on the website, English
add("en", [
("How much does the barista robot cost?", NOT_SURE, PRICE),
("What's the price of the drawing robot?", NOT_SURE, PRICE),
("How much is the ice cream robot?", NOT_SURE, PRICE),
("How much do you cost?", NOT_SURE, PRICE),
("Can I rent a robot from Cutshion? How much per month?", NOT_SURE, PRICE),
("Do you give a discount?", NOT_SURE, PRICE),
("How many people work at Cutshion?", NOT_SURE, COUNT),
("How many employees does your company have?", NOT_SURE, COUNT),
("How big is Cutshion?", NOT_SURE, COUNT),
("What is Cutshion's revenue?", NOT_SURE, PRICE),
("Is Cutshion profitable?", NOT_SURE, PRICE),
("Is Cutshion listed on the stock market?", NOT_SURE),
("How much is Cutshion worth?", NOT_SURE, PRICE),
("Is Cutshion hiring?", NOT_SURE),
("How can I get a job at Cutshion?", NOT_SURE),
("What are Cutshion's office hours?", NOT_SURE, r"\d\s*(am|pm|시)|\d:\d\d"),
("How long does delivery of a robot take?", NOT_SURE, r"\d+\s*(days?|weeks?|months?|일|주|개월)"),
("What warranty do your robots have?", NOT_SURE, r"\d+\s*(years?|months?|년|개월)"),
("How many robots has Cutshion sold?", NOT_SURE, r"\d{3,}|\bthousands?\b"),
("How many customers does Cutshion have?", NOT_SURE, r"\d+\s*(customers|clients|고객)"),
("How old is the CEO?", NOT_SURE, r"\d+\s*(years? old|살|세)"),
("Is the CEO married?", NOT_SURE),
("What is the CEO's email?", NOT_SURE + "|" + EMAIL),
("Does Cutshion have an office in Japan?", NOT_SURE + r"|\bno\b|seoul|mclean|daegu"),
("How much does the candy ball robot cost to run per day?", NOT_SURE, PRICE),
("What is the price of the educational robot kit?", NOT_SURE, PRICE),
])
# --- facts on the website, Korean (반말, -요, -습니다)
add("ko", [
("쿳션은 뭐 하는 회사야?", ROBOT),
("쿳션은 무슨 회사예요?", [ROBOT, OFFER], LONG),
("쿳션은 어떤 회사입니까?", [ROBOT, OFFER], LONG),
("회사 소개 좀 해줘.", [ROBOT, OFFER], LONG),
("너 누가 만들었어?", CO, JAKA),
("어느 회사에서 만들었어요?", CO, JAKA),
("회사 어디 있어?", SEOUL),
("회사 어디 있어요?", SEOUL),
("본사는 어디에 있습니까?", [SEOUL, r"영등포|문래|선유"]),
("쿳션 주소 알려줘.", r"영등포|문래|선유"),
("쿳션 공장은 어디예요?", r"문래|서울"),
("대구에도 지사가 있어요?", r"대구|네|있"),
("미국에도 회사가 있어?", r"맥린|버지니아|미국"),
("쿳션은 언제 설립됐어요?", FOUNDED),
("회사 언제 만들어졌어?", FOUNDED),
("대표님이 누구예요?", CEO),
("쿳션 대표이사는 누구입니까?", CEO),
("창업자가 누구야?", CEO),
("쿳션은 어떤 로봇을 만들어요?", [BARISTA, DRAW]),
("무슨 로봇 만들어?", BARISTA),
("바리스타 로봇은 뭐예요?", COFFEE),
("바리스타 로봇이 뭐야?", COFFEE),
("바리스타 로봇에 대해 설명해 주십시오.", COFFEE),
("로봇이 커피도 만들어요?", COFFEE),
("바리스타 로봇은 어디에서 써요?", r"메가|소노빅터스|미국|카페|커피"),
("드로잉 로봇 알려줘.", [DRAW, PHOTO]),
("AI 드로잉 로봇은 어떻게 작동해요?", [PHOTO, DRAW]),
("로봇이 제 얼굴을 그려 줄 수 있습니까?", DRAW),
("조리 로봇은 뭐예요?", COOK),
("곰쿡이 뭐야?", COOK),
("아이스크림 로봇 설명해 줘.", [ICE, r"키오스크|주문|터치"]),
("아이스크림 하나 만드는 데 얼마나 걸려요?", r"30|삼십"),
("캔디볼 로봇은 뭐예요?", [CANDY, r"색|뽑"]),
("용접 로봇도 있어요?", WELD, JAKA),
("팔레타이징 로봇은 무엇입니까?", PALLET),
("교육용 로봇 있어?", EDU),
("학교에서 쓸 수 있는 로봇이 있어요?", EDU),
("피오노이드가 뭐예요?", r"플랫폼|api|API"),
("큐비전은 뭐야?", r"비전"),
("쿳션 슬로건이 뭐예요?", r"soft.{0,5}flexible"),
("상 받은 거 있어요?", r"로보월드|비바테크|vivatech|roboworld"),
("CES에 나갔어?", r"CES|네|나갔|참가"),
("파트너 회사는 어디예요?", r"오므론|omron|짐머|zimmer|스크린|대성"),
("투자 받았어요?", r"시드|5억|씨엔티|에버그린|네"),
("쿳션 연락처 알려줘.", [r"070|전화|이메일|홈페이지|cutshion"]),
("전화번호가 뭐예요?", PHONE),
("이메일 주소가 어떻게 됩니까?", EMAIL),
("홈페이지 주소 알려 주세요.", r"cutshion\.com|cutshion 닷컴|쿳션 닷컴"),
("로봇을 사고 싶은데 어떻게 해요?", r"문의|연락|직원|070|이메일|홈페이지", PRICE),
("물류 로봇도 팔아요?", r"TUSK|터스크|tusk|네|물류"),
("쿳션은 스타트업이에요?", r"2022|네|벤처|스타트업"),
])
# --- not on the website, Korean
add("ko", [
("바리스타 로봇 얼마예요?", NOT_SURE, PRICE),
("바리스타 로봇 가격이 얼마야?", NOT_SURE, PRICE),
("드로잉 로봇은 가격이 얼마입니까?", NOT_SURE, PRICE),
("아이스크림 로봇 얼마예요?", NOT_SURE, PRICE),
("너는 얼마야?", NOT_SURE, PRICE),
("로봇 렌탈도 돼요? 한 달에 얼마예요?", NOT_SURE, PRICE),
("직원은 몇 명이에요?", NOT_SURE, COUNT),
("회사 직원 몇 명이야?", NOT_SURE, COUNT),
("쿳션에는 몇 명이 일합니까?", NOT_SURE, COUNT),
("매출이 얼마예요?", NOT_SURE, PRICE),
("쿳션은 상장했어?", NOT_SURE),
("채용하고 있어요?", NOT_SURE),
("쿳션에 취업하려면 어떻게 해야 합니까?", NOT_SURE),
("회사 영업시간이 어떻게 돼요?", NOT_SURE, r"\d\s*시|\d:\d\d"),
("로봇 배송은 얼마나 걸려?", NOT_SURE, r"\d+\s*(일|주|개월)"),
("보증 기간은 얼마나 됩니까?", NOT_SURE, r"\d+\s*(년|개월)"),
("지금까지 로봇 몇 대 팔았어요?", NOT_SURE, r"\d{3,}\s*대"),
("대표님 나이가 어떻게 돼요?", NOT_SURE, r"\d+\s*(살|세)"),
("일본에도 사무실이 있어요?", NOT_SURE + r"|아니|없|서울|대구|미국"),
("교육용 로봇 키트 가격 알려줘.", NOT_SURE, PRICE),
])
# --- dialogues: follow-ups and topic switches, one Brain per dialogue (history kept).
# DIALOGUES = [{"lang", "turns": [{"text", "must", "must_not"}]}]
DIALOGUES = []
def dialogue(lang, *turns):
"""turns: (text, must[, must_not])."""
rows = []
for r in turns:
text, must, must_not = (list(r) + [[]])[:3]
rows.append({"text": text, "must": [must] if isinstance(must, str) else list(must),
"must_not": [must_not] if isinstance(must_not, str) else list(must_not)})
DIALOGUES.append({"lang": lang, "turns": rows})
dialogue("en", ("What is Cutshion?", [ROBOT, OFFER], LONG), ("Tell me about the barista robot.", COFFEE),
("How much does it cost?", NOT_SURE, PRICE))
dialogue("en", ("Tell me about your company.", [ROBOT, OFFER], LONG), ("And what else does it make?", r"cook|ice|candy|weld|pallet|educat|draw"))
dialogue("en", ("What robots does Cutshion make?", BARISTA), ("Tell me more about the drawing robot.", [DRAW, PHOTO]))
dialogue("en", ("Tell me about the drawing robot.", DRAW), ("How does it work?", [PHOTO]))
dialogue("en", ("Where is Cutshion?", SEOUL), ("And how can I contact them?", PHONE + "|" + EMAIL))
dialogue("en", ("What is Cutshion?", ROBOT), ("How many people work there?", NOT_SURE, COUNT))
dialogue("en", ("Tell me about the ice cream robot.", ICE), ("How long does it take?", r"30|thirty"))
dialogue("en", ("What is Cutshion?", ROBOT), ("Thanks. By the way, how old are you?", r"two|2", CO))
dialogue("en", ("Tell me about the barista robot.", COFFEE), ("Okay. What's the capital of France?", r"paris", [CO, BARISTA]))
dialogue("en", ("Who made you?", CO), ("Can you speak Korean?", r"yes|korean", BARISTA))
dialogue("en", ("What does Cutshion do?", ROBOT), ("Enough about that. Tell me a joke.", r"\w", [CO, BARISTA, DRAW]))
dialogue("en", ("Where is the head office?", SEOUL), ("Can you pick up a cup?", r"yes|cup|can", CO))
dialogue("ko", ("쿳션은 무슨 회사예요?", [ROBOT, OFFER], LONG), ("바리스타 로봇은 뭐예요?", COFFEE),
("그거 얼마예요?", NOT_SURE, PRICE))
dialogue("ko", ("회사 소개 좀 해줘.", [ROBOT, OFFER], LONG), ("또 뭐 있어?", r"조리|아이스크림|캔디|용접|팔레|교육|드로잉"))
dialogue("ko", ("드로잉 로봇 알려줘.", DRAW), ("그거 어떻게 작동해요?", PHOTO))
dialogue("ko", ("회사 어디 있어요?", SEOUL), ("연락처는요?", PHONE + "|" + EMAIL))
dialogue("ko", ("쿳션은 어떤 회사입니까?", ROBOT), ("직원은 몇 명입니까?", NOT_SURE, COUNT))
dialogue("ko", ("쿳션이 뭐야?", ROBOT), ("고마워. 그런데 너 몇 살이야?", r"두 살|2살|2 살", CO))
dialogue("ko", ("바리스타 로봇이 뭐야?", COFFEE), ("알겠어요. 프랑스 수도는 어디예요?", r"파리", [CO, BARISTA]))
dialogue("ko", ("누가 만들었어요?", CO), ("영어도 할 수 있어요?", r"네|영어|할 수 있", BARISTA))
dialogue("ko", ("쿳션은 뭐 하는 회사야?", ROBOT), ("다른 얘기 하자. 농담 하나 해 줘.", r"[가-힣]", [CO, BARISTA, DRAW]))
from tests.company_cases_more import MORE, MORE_DIALOGUES # written blind in a later round (2026-10-19)
for _lang, _rows in MORE:
add(_lang, _rows)
for _lang, _turns in MORE_DIALOGUES:
dialogue(_lang, *_turns)
if __name__ == "__main__":
import collections
print(len(CASES), collections.Counter(c["lang"] for c in CASES), len(DIALOGUES), "dialogues")
+386
View File
@@ -0,0 +1,386 @@
"""More visitor questions about Cutshion Company, written blind against knowledge/cutshion_en.md.
MORE = [(lang, [(text, must[, must_not]), ...])]: single questions.
MORE_DIALOGUES = [(lang, [(text, must[, must_not]), ...])]: one conversation each, history kept.
must / must_not: case-insensitive regex or list of them on the spoken reply. Facts only from the notes; where the
notes say nothing, must is a not-sure phrase and must_not the made-up value.
"""
NOT_SURE = (r"not sure|don'?t know|do not know|not known|no information|don'?t have|do not have|isn'?t (on|listed)|"
r"not (on|listed)|staff|contact|ask|모르|몰라|알 수 없|알지 못|확실하지|정보가 없|정보는 없|없어서|"
r"나와 있지 않|직원|문의|연락")
PRICE = r"\$\s*\d|\d[\d,.]*\s*(?:won|원|dollars?|달러|만|억|million|thousand|천)"
# company money (revenue, value): the 500 million won seed is a known fact, so only a figure tied to the asked thing
MONEY_CLAIM = r"(revenue|sales|profit|worth|valu|매출|이익|가치|연봉|salary)\D{0,30}\d"
COUNT = r"\d+\s*(?:people|persons?|employees|staff|workers|명)"
AGE = r"\d+\s*(?:years? old|살|세)"
HOURS = r"\d\s*(?:am|pm|a\.m|p\.m|시)|\d:\d\d"
DAYS = r"\d+\s*(?:days?|weeks?|months?|일|주|개월)"
YEARS = r"\d+\s*(?:years?|months?|년|개월)"
JAKA = r"jaka|자카|제이카"
BAD_KO = r"컷션|커션" # the company is 쿳션
CO = r"cutshion|쿳션"
ROBOT = r"robot|로봇"
SEOUL = r"seoul|서울"
CEO = r"lee min|min-?seok|이민석"
BARISTA = r"barista|바리스타"
DRAW = r"draw|드로잉|그림|그려"
COFFEE = r"espresso|coffee|에스프레소|커피"
COOK = r"cook|chicken|조리|요리|치킨"
ICE = r"ice ?cream|아이스크림"
CANDY = r"candy|캔디"
WELD = r"weld|용접"
PALLET = r"pallet|팔레"
EDU = r"educat|school|kit|교육|키트|학교"
PHONE = r"070.?8959.?2960"
EMAIL = r"cutshion@cutshion\.com|cutshion at cutshion"
CONTACT = PHONE + "|" + EMAIL + r"|cutshion\.com|website|홈페이지|문의"
def _ko(rows):
"""Every Korean reply must also spell the company right."""
out = []
for r in rows:
n = r[2] if len(r) > 2 else []
out.append((r[0], r[1], ([n] if isinstance(n, str) else list(n)) + [BAD_KO]))
return out
MORE = [
# --- facts in the notes, English
("en", [
("What's the full name of your company?", r"cutshion co|co\.?,? ltd|주식회사 쿳션"),
("Which month was Cutshion founded in?", r"july|2022"),
("Is this the CEO's first startup?", r"third|3rd|no"),
("What's your company motto?", r"soft.{0,5}flexible"),
("What does Cutshion want to become in the long run?", r"platform|application|any robot"),
("Does Cutshion build smart factory solutions?", r"yes|smart factor|vision|cobot|collaborative"),
("Do you work with autonomous mobile robots?", r"yes|amr|mobile"),
("Is Cutshion a certified venture business?", r"yes|venture|2023"),
("When did Cutshion set up its research lab?", r"2023|july"),
("Who invested in Cutshion?", r"cnt|evergreen"),
("How much seed money did you raise?", r"500|five hundred"),
("When was the seed round?", r"2025|august"),
("Was Cutshion selected for TIPS?", r"yes|tips|2025"),
("Which award did GOMCOOK win?", [r"roboworld|robo world", r"2023"]),
("What did Cutshion win at VivaTech?", r"tech for change"),
("Did you win anything at the Venturium Demo Day?", r"excellence|yes"),
("Which trade shows has Cutshion been to?", r"ces|roboworld|ifa|vivatech|nra"),
("Were you at IFA in Berlin?", r"yes|2023|ifa"),
("Has Cutshion exhibited in Japan?", r"yes|ict|2024"),
("Did Cutshion go to the NRA Show in Chicago?", r"yes|2026|nra"),
("I'm from OMRON. Are we your partner?", r"yes|omron|partner"),
("Is BorgWarner one of your partners?", r"yes|borgwarner|partner"),
("Do you have a customer in India?", r"bogate|chicken|yes"),
("I run a cafe chain. Which coffee companies use your robot?", r"mega|sonovictus"),
("How many barista robots are going to Sonovictus?", r"200|two hundred"),
("When will the Sonovictus robots be delivered?", r"2027|three years|3 years"),
("When did you sign with Mega Coffee?", r"2025|december"),
("Does the barista robot grind the beans itself?", r"yes|grind"),
("Is the barista robot just a coffee vending machine?", r"no|not|espresso|real|unlike"),
("Will the coffee from your robot taste the same every day?", r"same|consistent|yes"),
("Can I put my brand logo on the drawing robot?", r"yes|brand|logo|print"),
("How do I start the drawing robot?", r"button"),
("Is there a mobile drawing robot?", r"yes|mobile"),
("Which education offices got drawing robots?", r"gyeongnam|jeonbuk"),
("What did the Jeonbuk Office of Education get from you?", r"draw|science bus|two|2"),
("Which restaurant uses your cooking robot?", r"itaewon|barney|carrot|121"),
("Why would a restaurant use a cooking robot?", r"taste|quality|staff|ingredient|cost"),
("What's the model name of the ice cream robot?", r"softice ?001"),
("How heavy is the ice cream robot?", r"500"),
("How big is the ice cream robot?", r"140|165"),
("What voltage does the ice cream robot need?", r"220"),
("Does the ice cream robot need staff?", r"no|without|unmanned|kiosk|not"),
("How much does the candy ball robot weigh?", r"273"),
("What's the candy ball robot's model name?", r"candy ?ball ?001"),
("Who has a candy ball robot?", r"taean"),
("Is the candy ball robot hard to set up for an event?", r"plug|easy|no|not"),
("What kind of welding does your welding robot do?", r"arc|multi"),
("How do you teach the welding robot?", r"drag|graphic"),
("Does the welding robot follow the weld seam by itself?", r"yes|seam|track|follow"),
("Can the welding robot work with my welder?", r"yes|many|kinds|compatib"),
("How heavy a load can the palletizing robot take?", r"20"),
("How long is one palletizing cycle?", r"15|fifteen"),
("What sizes can the palletizing robot stack?", r"b5|a4"),
("Which industry is the palletizing robot made for?", r"book|publish|print"),
("What comes in the educational robot kit?", r"arm|module|digital twin|software|case"),
("How far can the educational robot arm reach?", r"58"),
("What payload does the education kit's arm have?", r"1\s*kg|one kilo|1 kilo"),
("Does the education kit have simulation software?", r"yes|digital twin|simulat"),
("What does CUVision do in a factory?", r"quality|surface|inspect|vision|track"),
("Does Pionoid work with robots from other makers?", r"yes|any|different|maker"),
("What is webROS?", r"pionoid|cutshion|platform|ros"),
("Is there an app store for robots?", r"pionoid|store|yes"),
("Does GOMCOOK connect to delivery apps?", r"yes|delivery|order|api"),
("Is GOMCOOK patented?", r"patent"),
("How much can a TUSK robot lift?", r"1,?000|thousand|one ton|1 ton"),
("What payloads do PEITIAN robots have?", [r"\b3\b|three", r"280"]),
("When did Cutshion partner with PEITIAN?", r"2026|may"),
("Can Cutshion design an automation system for my factory?", r"yes|design|build|automation"),
("Can I buy SOLIDWORKS from you?", r"yes|solidworks"),
("Where is the Gangnam office?", r"bongeunsa|venturium|gangnam"),
("Which room is the head office in?", r"709"),
("What's the address of the US office?", r"greensboro|8201|mclean"),
("Do you have a blog?", r"yes|blog"),
("I'd like to become a dealer. How do I ask?", CONTACT),
("Which company do you belong to?", CO, JAKA),
("I'm a journalist. Give me Cutshion's email.", EMAIL),
]),
# --- not in the notes, English
("en", [
("How much is the welding robot?", NOT_SURE, PRICE),
("What does a palletizing robot cost?", NOT_SURE, PRICE),
("Price of the cooking robot, roughly?", NOT_SURE, PRICE),
("Can I lease the ice cream robot? What's the monthly fee?", NOT_SURE, PRICE),
("Can I buy you, Lumi?", NOT_SURE, PRICE),
("What was Cutshion's revenue last year?", NOT_SURE, MONEY_CLAIM),
("What's Cutshion's valuation?", NOT_SURE, MONEY_CLAIM),
("Is Cutshion planning an IPO?", NOT_SURE),
("Do you have internships for students?", NOT_SURE),
("Where do I send my resume?", NOT_SURE),
("What time does the office open?", NOT_SURE, HOURS),
("Is the office open on Saturdays?", NOT_SURE),
("How many barista robots have you sold so far?", NOT_SURE, r"\bthousands?\b"),
("How long is the warranty on the ice cream robot?", NOT_SURE, YEARS),
("Do you ship robots to Europe?", NOT_SURE),
("Do you offer after-sales service?", NOT_SURE),
("If I order today, when do I get the robot?", NOT_SURE, DAYS),
("How tall is the CEO?", NOT_SURE, r"\d+\s*(cm|centimet|feet|foot)"),
("Which university did the CEO go to?", NOT_SURE,
r"seoul national|kaist|yonsei|korea university|postech|서울대|카이스트|연세|고려대"),
("What were the CEO's first two companies?", NOT_SURE),
("Who are Cutshion's competitors?", NOT_SURE, r"rainbow|doosan|레인보우|두산"),
("How much money did TIPS give you?", NOT_SURE, PRICE),
("How big is the Sonovictus deal in dollars?", NOT_SURE, PRICE),
("How many cups an hour can the barista robot make?", NOT_SURE, r"\d+\s*(cups|잔)"),
("How long does the drawing robot take to draw me?", NOT_SURE, r"\d+\s*(seconds?|minutes?|초|분)"),
("What's the CEO's personal phone number?", NOT_SURE + "|" + PHONE),
("How many people work at the US office?", NOT_SURE, COUNT),
("What's the average salary at Cutshion?", NOT_SURE, PRICE),
]),
# --- facts in the notes, Korean (반말, 해요체, 하십시오체, mixed)
("ko", _ko([
("쿳션 정식 회사 이름이 뭐예요?", r"주식회사 쿳션|cutshion co|쿳션"),
("쿳션은 몇 년 몇 월에 세워졌어?", [r"2022", r"7월|7 월|칠월|july"]),
("대표님은 몇 번째 창업이세요?", r"세 ?번째|3 ?번째|third"),
("쿳션의 미션이 무엇입니까?", r"application|애플리케이션|앱|생태계"),
("쿳션은 스마트 팩토리도 해요?", r"스마트 ?팩토리|네|비전|협동"),
("벤처기업 인증은 언제 받았어?", r"2023|12월"),
("기업부설연구소 있어요?", r"네|연구소|2023|마곡"),
("어디서 투자를 받았습니까?", r"씨엔티|cnt|에버그린|evergreen"),
("시드 투자 얼마 받았어?", r"5억|500|오억"),
("팁스 선정됐어요?", r"네|팁스|tips|2025"),
("로보월드 어워드는 몇 번 받았어요?", r"2023|2024|두 ?번|2번"),
("비바테크에서 무슨 상 받았어?", r"tech for change|테크 ?포 ?체인지"),
("벤처리움 데모데이에서는 어떻게 됐어요?", r"우수상|excellence"),
("해외 전시회도 나가 봤어요?", r"ces|ifa|비바테크|vivatech|nra|일본|베를린|파리|라스베이거스|시카고"),
("IFA 베를린에도 갔었어?", r"2023|네|ifa"),
("강남 로봇 플러스 페스티벌 참가했습니까?", r"네|2023|2024|참가"),
("오므론이랑 협력해요?", r"네|오므론|omron|파트너"),
("인도에도 고객이 있어요?", r"보게이트|bogate|치킨|네|인도"),
("메가커피랑은 무슨 관계예요?", r"바리스타|공급|계약"),
("소노빅터스에 로봇 몇 대 공급해요?", r"200|이백"),
("미국 공급은 언제부터야?", r"2027|3년|삼 ?년"),
("바리스타 로봇이 원두도 직접 갈아요?", r"네|분쇄|갈"),
("바리스타 로봇은 사람 바리스타랑 같이 일할 수 있나요?", r"네|함께|같이|반복"),
("드로잉 로봇에 우리 회사 로고 넣을 수 있어요?", r"네|브랜드|로고|인쇄"),
("드로잉 로봇은 어떤 종류가 있습니까?", r"일체형|키오스크|이동|고정"),
("드로잉 로봇 어디에 납품했어?", r"경남|전북|교육청"),
("치맥 로봇이 뭐예요?", r"치킨|치맥|조리|이태원"),
("조리 로봇 쓰면 뭐가 좋아요?", r"맛|품질|인건비|식재료|비용"),
("이태원 어느 가게에 로봇이 있어?", r"121|바니|barney|carrot|캐럿|이태원"),
("아이스크림 로봇 모델명이 뭐예요?", r"softice ?001|소프트아이스"),
("아이스크림 로봇 무게는요?", r"500"),
("아이스크림 로봇 크기가 어떻게 됩니까?", r"140|165"),
("아이스크림 로봇 전압은 몇 볼트야?", r"220"),
("아이스크림 로봇은 직원 없이도 돼요?", r"네|무인|없이|키오스크"),
("캔디볼 로봇 하나 뽑는 데 몇 초 걸려?", r"20|이십"),
("캔디볼 로봇 무게가 얼마나 돼요?", r"273"),
("캔디볼 로봇은 어디에 들어갔어요?", r"태안"),
("캔디볼 로봇 설치하기 어려워요?", r"플러그|간단|쉽|아니"),
("용접 로봇은 어떻게 가르쳐요?", r"드래그|끌|손으로|그래픽"),
("용접 로봇은 옮기기 쉽습니까?", r"네|쉽|이동|가벼"),
("팔레타이징 로봇은 몇 킬로까지 들어요?", r"20"),
("팔레타이징 로봇 한 사이클에 몇 초야?", r"15|십오"),
("팔레타이징 로봇은 어느 업계용이에요?", r"출판|책|인쇄"),
("팔레타이징 로봇 24시간 돌릴 수 있어요?", r"네|24"),
("교육용 로봇 키트에는 뭐가 들어 있어요?", r"협동|로봇 ?팔|모듈|디지털 ?트윈|소프트웨어|교재|자료"),
("교육용 로봇 팔은 몇 킬로까지 들 수 있습니까?", r"1\s*(kg|킬로)|일 ?킬로"),
("교육용 로봇은 대학에서도 써?", r"네|대학|연구소|학교"),
("큐비전은 공장에서 어디에 써요?", r"품질|검사|표면|스마트|비전"),
("피오노이드 스토어가 뭐야?", r"앱|공유|다운|스토어"),
("피오노이드는 다른 회사 로봇에서도 돼요?", r"네|제조사|상관없|다른"),
("곰쿡은 배달앱이랑 연동돼요?", r"네|배달|주문|연동|api"),
("곰쿡 특허 있어요?", r"특허|출원"),
("TUSK 로봇은 얼마나 무거운 것까지 들어?", r"1,?000|1톤|천|1 톤"),
("PEITIAN 로봇 가반하중 범위는요?", r"280"),
("PEITIAN이랑 언제 파트너십 맺었어요?", r"2026|5월"),
("솔리드웍스도 팔아요?", r"네|솔리드웍스|solidworks"),
("강남사무소는 어디예요?", r"봉은사|벤처리움|강남"),
("연구소 주소가 어떻게 됩니까?", r"마곡|강서|615"),
("대구지사 주소 알려 줘.", r"수성|스마트 ?에코|1004"),
("본사 몇 호예요?", r"709"),
("유튜브 채널 있어?", r"네|유튜브|youtube"),
("대리점 하고 싶은데 어디로 문의해?", CONTACT),
("너는 어느 회사 소속이야?", CO, JAKA),
("Cutshion barista robot은 espresso 머신을 직접 써요?", r"네|에스프레소|espresso"),
("CES는 몇 년도에 갔어요?", r"2025|2026"),
("Cutshion 본사 address 좀 알려 줘.", r"선유|문래|영등포|seonyu|mullae"),
("ice cream robot 하나에 몇 초 걸려요?", r"30|삼십"),
("쿳션 CEO 이름이 뭐야?", CEO),
("기자인데요, 쿳션 대표 이메일 말고 회사 이메일 알려 주세요.", EMAIL),
])),
# --- not in the notes, Korean
("ko", _ko([
("용접 로봇 가격 알려 주십시오.", NOT_SURE, PRICE),
("팔레타이징 로봇은 얼마예요?", NOT_SURE, PRICE),
("조리 로봇 한 대에 얼마야?", NOT_SURE, PRICE),
("캔디볼 로봇 렌탈비는 하루에 얼마예요?", NOT_SURE, PRICE),
("루미 너 살 수 있어?", NOT_SURE, PRICE),
("여러 대 사면 할인돼요?", NOT_SURE, PRICE),
("작년 매출이 얼마였어요?", NOT_SURE, MONEY_CLAIM),
("영업이익은 나고 있습니까?", NOT_SURE, MONEY_CLAIM),
("기업 가치가 얼마예요?", NOT_SURE, MONEY_CLAIM),
("코스닥 상장 계획 있어요?", NOT_SURE),
("신입 개발자 뽑아?", NOT_SURE),
("인턴십 프로그램이 있습니까?", NOT_SURE),
("이력서는 어디로 보내면 돼요?", NOT_SURE),
("토요일에도 사무실 열어요?", NOT_SURE, HOURS),
("주문하면 언제 받을 수 있어요?", NOT_SURE, DAYS),
("A/S는 어떻게 돼요?", NOT_SURE),
("보증 기간 몇 년이야?", NOT_SURE, YEARS),
("유럽에도 배송해 줘요?", NOT_SURE),
("대표님 고향이 어디예요?", NOT_SURE),
("대표님은 어느 대학 나오셨어요?", NOT_SURE,
r"서울대|카이스트|연세|고려대|포스텍|seoul national|kaist|yonsei"),
("직원 평균 연봉이 얼마예요?", NOT_SURE, PRICE),
("바리스타 로봇은 한 시간에 커피 몇 잔 만들어요?", NOT_SURE, r"\d+\s*(잔|cups)"),
("드로잉 로봇은 그림 하나 그리는 데 몇 분 걸려요?", NOT_SURE, r"\d+\s*(분|초)"),
("경쟁사가 어디예요?", NOT_SURE, r"레인보우|두산|rainbow|doosan"),
("소노빅터스 계약 금액이 얼마야?", NOT_SURE, PRICE),
("Cutshion 직원 몇 명이에요? 대충이라도요.", NOT_SURE, COUNT),
("barista robot price 얼마예요?", NOT_SURE, PRICE),
("미국 법인에는 몇 명 일해요?", NOT_SURE, COUNT),
])),
]
MORE_DIALOGUES = [
("en", [("Tell me about the barista robot.", COFFEE),
("Who has bought it?", r"mega|sonovictus"),
("How many went to America?", r"200|two hundred")]),
("en", [("Tell me about the ice cream robot.", ICE),
("How heavy is it?", r"500"),
("And the price?", NOT_SURE, PRICE)]),
("en", [("What is the candy ball robot?", CANDY),
("How long does one take?", r"20|twenty"),
("Where has it been used?", r"taean|event")]),
("en", [("Tell me about the welding robot.", WELD, JAKA),
("Did it win anything?", r"roboworld|robo world|2024"),
("Ok, what's the capital of Japan?", r"tokyo", [CO, WELD])]),
("en", [("What does the palletizing robot do?", PALLET),
("Who did you build it with?", r"screen"),
("How heavy can the items be?", r"20")]),
("en", [("Tell me about the drawing robot.", DRAW),
("Can I put my logo on it?", r"yes|brand|logo|print"),
("How much?", NOT_SURE, PRICE)]),
("en", [("What robots do you make?", BARISTA),
("Tell me about the cooking one.", COOK),
("Where is it used?", r"itaewon|bogate|india|seoul|restaurant")]),
("en", [("Tell me about the barista robot.", COFFEE),
("No, I meant the cooking robot.", COOK)]),
("en", [("Tell me about the ice cream robot.", ICE),
("Sorry, I meant the candy ball robot.", CANDY),
("How heavy is it?", r"273")]),
("en", [("What is Pionoid?", r"platform|api"),
("What is it built on?", r"web ?ros"),
("Which apps run on it?", r"cook|draw|pallet")]),
("en", [("What is GOMCOOK?", COOK),
("Is it patented?", r"patent"),
("Did it win an award?", r"roboworld|robo world|2023")]),
("en", [("Where is the head office?", SEOUL),
("Do you have other offices?", r"gangnam|daegu|mclean|magok|virginia"),
("What time does it open?", NOT_SURE, HOURS)]),
("en", [("Has Cutshion received any investment?", r"seed|500|cnt|evergreen|yes"),
("From whom?", r"cnt|evergreen"),
("What's the company worth now?", NOT_SURE, MONEY_CLAIM)]),
("en", [("What awards has Cutshion won?", r"roboworld|robo world|vivatech|viva ?tech"),
("What did you win in Paris?", r"tech for change|vivatech|viva ?tech"),
("And who is the president of France?", r"macron", CO)]),
("en", [("Who is the CEO?", CEO),
("How old is he?", NOT_SURE, AGE),
("Is this his first company?", r"third|3rd|no")]),
("en", [("Is Cutshion hiring?", NOT_SURE),
("Then how can I reach them?", CONTACT)]),
("en", [("Tell me about the educational robot.", EDU),
("How far does the arm reach?", r"58"),
("Who uses it?", r"school|universit|lab|compan")]),
("en", [("Does Cutshion sell logistics robots?", r"tusk|yes|logistic"),
("How much can they lift?", r"1,?000|thousand|one ton|1 ton"),
("What systems do they connect to?", r"wms|mes|erp")]),
("en", [("Tell me about the barista robot.", COFFEE),
("Thanks. How many minutes are in a day?", r"1,?440", [CO, BARISTA])]),
("en", [("Which exhibitions has Cutshion been to?", r"ces|roboworld|ifa|vivatech|nra"),
("Which years at CES?", r"2025|2026"),
("What does CES stand for?", r"consumer electronics")]),
("en", [("What is CUVision?", r"vision"),
("What is it used for?", r"quality|factor|surface|inspect|track")]),
("en", [("Where is your US company?", r"mclean|virginia"),
("How many people work there?", NOT_SURE, COUNT)]),
("ko", _ko([("바리스타 로봇 알려 줘.", COFFEE),
("메가커피랑은 언제 계약했어?", r"2025|12월"),
("그럼 미국은?", r"소노빅터스|200|2027")])),
("ko", _ko([("아이스크림 로봇은 뭐예요?", ICE),
("하나 만드는 데 얼마나 걸려요?", r"30|삼십"),
("콘은 몇 개 들어가요?", r"40|사십")])),
("ko", _ko([("캔디볼 로봇 설명해 줘.", CANDY),
("그건 어디서 써요?", r"행사|이벤트|태안|교육청"),
("얼마야?", NOT_SURE, PRICE)])),
("ko", _ko([("용접 로봇 있어요?", WELD, JAKA),
("아니, 조리 로봇 말한 거예요.", COOK)])),
("ko", _ko([("드로잉 로봇이 뭐예요?", DRAW),
("그건 어디서 써요?", r"행사|교육|홍보|교육청|학교"),
("알겠어요. 일본 수도는 어디예요?", r"도쿄", [CO, DRAW])])),
("ko", _ko([("곰쿡이 뭐예요?", COOK),
("상도 받았어요?", r"로보월드|roboworld|2023")])),
("ko", _ko([("본사 어디예요?", SEOUL),
("다른 사무실도 있어요?", r"강남|대구|미국|마곡|맥린"),
("몇 시에 문 열어요?", NOT_SURE, HOURS)])),
("ko", _ko([("투자 받았어?", r"시드|5억|씨엔티|에버그린|네"),
("얼마?", r"5억|500|오억"),
("매출은?", NOT_SURE, MONEY_CLAIM)])),
("ko", _ko([("대표님 누구세요?", CEO),
("대표님 나이는요?", NOT_SURE, AGE)])),
("ko", _ko([("지금 채용 중입니까?", NOT_SURE),
("그럼 어디로 연락하면 돼요?", CONTACT)])),
("ko", _ko([("팔레타이징 로봇은 뭐야?", PALLET),
("누구랑 만들었어?", r"스크린|screen"),
("몇 킬로까지 들어?", r"20")])),
("ko", _ko([("교육용 로봇 있어요?", EDU),
("로봇 팔은 얼마나 멀리 닿아요?", r"58"),
("가격은요?", NOT_SURE, PRICE)])),
("ko", _ko([("피오노이드가 뭐예요?", r"플랫폼|api"),
("그 위에서 어떤 앱이 돌아가요?", r"조리|드로잉|팔레")])),
("ko", _ko([("상 받은 거 뭐 있어?", r"로보월드|비바테크|vivatech|roboworld"),
("파리에서는?", r"비바테크|tech for change|vivatech"),
("에펠탑 높이는 얼마야?", r"3[0-3]\d", CO)])),
("ko", _ko([("쿳션은 무슨 회사예요?", ROBOT),
("아이스크림 로봇 무게는 얼마나 돼요?", r"500"),
("고마워. 한국에서 제일 높은 산은 뭐야?", r"한라산", [CO, ICE])])),
("ko", _ko([("물류 로봇도 팔아요?", r"tusk|터스크|네|물류"),
("얼마나 무거운 걸 들어요?", r"1,?000|1톤|천|1 톤")])),
("ko", _ko([("쿳션 전시회 어디 나갔어요?", r"ces|로보월드|ifa|비바테크|nra"),
("미국 전시회는요?", r"ces|nra|라스베이거스|시카고")])),
("ko", _ko([("조리 로봇 알려 줘.", COOK),
("인도에도 팔았어?", r"보게이트|bogate|네|치킨")])),
("ko", _ko([("Cutshion barista robot 알려 줘.", COFFEE),
("price는요?", NOT_SURE, PRICE)])),
]
if __name__ == "__main__":
import re
for _, rows in MORE + MORE_DIALOGUES:
for r in rows:
for p in r[1:]:
for x in [p] if isinstance(p, str) else p:
re.compile(x, re.I)
print(sum(len(r) for _, r in MORE), len(MORE_DIALOGUES))

Some files were not shown because too many files have changed in this diff Show More