andito's picture
andito HF Staff
Data, training code and reproduction steps for reachy-gestures
0cc835c verified
Raw History Blame Contribute Delete
4.82 kB
"""Gesture label set, teacher prompt, and an LLM labeller shared by data generation and evaluation."""
import json
import re
import time
from pathlib import Path
from huggingface_hub import InferenceClient
HERE = Path(__file__).parent
DESCRIPTIONS = json.loads((HERE / "move_descriptions.json").read_text())
_PHRASES = json.loads((HERE / "gesture_phrases.json").read_text())
# Moves the robot may play while speaking, and while listening to the user (same split as the app's phrase list).
SAY_MOVES = [e["move"] for e in _PHRASES if e["move"] and e["say"]]
REACT_MOVES = [e["move"] for e in _PHRASES if e["move"] and (e["react"] or e["move"] == "relief1")]
MOVES = {"say": SAY_MOVES, "react": REACT_MOVES}
EXAMPLES = {(e["move"], k): (e[k] or e["say"])[:3] for e in _PHRASES if e["move"] for k in ("say", "react")}
KIND_TEXT = {
"say": (
"The robot itself is about to SAY the sentence aloud. Pick the gesture that acts out what the robot is saying, "
"as a human speaker would gesture while saying it."
),
"react": (
"The USER just said the sentence to the robot. Pick the gesture the robot should make in reaction while "
"it listens, before it answers (e.g. sad news gets a sad look, a threat gets fear, an insult gets irritation, "
"stress gets a calming gesture)."
),
}
RULES = """Rules:
- Reachy Mini is a small, friendly desk robot with an expressive head and antennas. It talks with people in many languages.
- Most sentences in a conversation are neutral (facts, instructions, questions, small talk, filler). Those get "none".
Only pick a gesture when the sentence clearly carries that emotion or intent. When in doubt, "none".
- Read meaning, not keywords: a negated emotion ("I'm not sad", "that's not scary") never gets that gesture, but
if the sentence then expresses another feeling ("I'm not sad anymore, I feel great!", "my dog didn't die, he's fine")
pick the gesture for that feeling (happy, relieved...);
emotion words used neutrally ("the film is called Happy Feet", "what does disgusted mean?") get "none";
implied emotion counts ("my flight got cancelled again" from the user is downcast/irritated material).
- Questions asking the other person about something (even about feelings, "are you scared?") are usually "none".
- "best" is the single best gesture or "none". "ok" lists every gesture that would also look fine (include "best";
for "none" you may add gestures that would be acceptable but not necessary, or leave it as ["none"]).
- The language of the sentence does not matter; judge the meaning."""
def system_prompt(kind: str) -> str:
lines = [f"You choose head gestures for the robot Reachy Mini. {KIND_TEXT[kind]}", "", "Gestures:"]
for move in MOVES[kind]:
examples = "; ".join(EXAMPLES[(move, kind)])
lines.append(f"- {move}: {DESCRIPTIONS[move]} Examples: {examples}")
lines.append('- none: no gesture (the default for neutral sentences).')
lines += ["", RULES, "", 'Answer with JSON only: [{"i": <index>, "best": "<gesture>", "ok": ["<gesture>", ...]}, ...]']
return "\n".join(lines)
def _parse(text: str, n: int, kind: str) -> list[dict] | None:
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
match = re.search(r"\[.*\]", text, flags=re.S)
if not match:
return None
try:
items = json.loads(match.group(0))
except json.JSONDecodeError:
return None
valid = set(MOVES[kind]) | {"none"}
out: list[dict | None] = [None] * n
for item in items:
i, best = item.get("i"), item.get("best")
if not isinstance(i, int) or not 0 <= i < n or best not in valid:
continue
ok = [m for m in item.get("ok", []) if m in valid]
out[i] = {"best": best, "ok": sorted(set(ok) | {best})}
return None if any(o is None for o in out) else out # type: ignore[return-value]
def label_batch(client: InferenceClient, model: str, kind: str, sentences: list[str], retries: int = 4) -> list[dict] | None:
user = "Sentences:\n" + "\n".join(f"{i}. {s}" for i, s in enumerate(sentences))
for attempt in range(retries):
try:
response = client.chat_completion(
model=model,
messages=[{"role": "system", "content": system_prompt(kind)}, {"role": "user", "content": user}],
max_tokens=6000,
temperature=0.0,
)
parsed = _parse(response.choices[0].message.content or "", len(sentences), kind)
if parsed:
return parsed
except Exception as error: # noqa: BLE001 - provider hiccups are retried
print(f" {model} attempt {attempt}: {type(error).__name__}: {str(error)[:160]}")
time.sleep(3 * (attempt + 1))
return None