"""Generate candidate sentences with several LLMs: python generate.py out.jsonl model[,model...] repeats seed [fraction] Each request asks for 20 sentences in one language aimed at one gesture or one hard category. The target is only a diversity device: every sentence is labelled blind afterwards by label.py. """ import re import sys import json import random import threading from pathlib import Path from concurrent.futures import ThreadPoolExecutor from huggingface_hub import InferenceClient from labels import MOVES, DESCRIPTIONS LANGUAGES = ["English", "French", "Spanish", "German", "Italian", "Portuguese", "Dutch", "Polish", "Russian", "Turkish", "Arabic", "Hindi", "Chinese (Mandarin)", "Japanese", "Korean"] TOPICS = ["weather", "cooking and food", "school and homework", "music", "sports", "pets", "work and the office", "health and doctors", "travel and holidays", "the robot itself", "games and puzzles", "jokes", "science", "family", "friends and relationships", "movies and TV", "shopping", "the news", "hobbies and crafts", "technology and gadgets", "money", "birthdays and parties", "nature and animals", "sleep and mornings", "a museum or exhibition demo", "a classroom with kids", "an elderly person living alone", "a hackathon"] SPEAKERS = {"say": ["a cheerful assistant robot", "a calm, kind robot", "a playful, curious robot", "a concise robot"], "react": ["a child", "a teenager", "an adult", "an elderly person", "an engineer testing the robot", "a visitor at a demo booth", "a tired parent"]} WHO = {"say": "the robot Reachy Mini says to the person it talks with", "react": "a person says to the robot Reachy Mini"} HARD = { "neutral": "neutral sentences with no particular emotion: facts, answers, instructions, plans, questions, small talk", "neutral_short": "very short neutral turns and fillers (one to five words), acknowledgements, hesitations, back-channel words", "negation": "sentences that mention an emotion but negate it, or deny a feeling, or say a bad/good thing did NOT happen", "keyword_neutral": "neutral sentences that contain emotional words without expressing that emotion (titles, definitions, " "quoting, asking about a word, describing a fictional character, reported speech about a third person)", "implied": "sentences that never name an emotion but clearly imply a strong feeling through the situation described", "question_feelings": "questions about feelings or opinions (asking, not expressing)", "mixed": "two-sentence turns where one sentence is neutral and the other expresses a clear feeling", } ASR_STYLE = ("Write them as raw speech-recognition transcripts: mostly lowercase, little or no punctuation, " "some fillers (um, uh, like), occasional repeated words.") def requests(kind: str, rng: random.Random) -> list[dict]: out = [] for language in LANGUAGES: weight = 3 if language == "English" else 1 for _ in range(weight): for move in MOVES[kind]: out.append({"kind": kind, "target": move, "language": language}) for hard in HARD: out.append({"kind": kind, "target": hard, "language": language}) out.append({"kind": kind, "target": "neutral", "language": language}) # neutral is the most common case # FOCUS="irritated1:3,implied:2" repeats the requests for targets the student still gets wrong import os focus = dict((k, int(v)) for k, v in (x.split(":") for x in os.environ.get("FOCUS", "").split(",") if x)) out = [r for r in out for _ in range(focus.get(r["target"], 1))] for r in out: r["topic"] = rng.choice(TOPICS) r["speaker"] = rng.choice(SPEAKERS[r["kind"]]) r["asr"] = r["kind"] == "react" and rng.random() < 0.35 return out def prompt(r: dict) -> str: if r["target"] in HARD: what = HARD[r["target"]] else: what = f"sentences where the gesture '{r['target']}' fits clearly. Gesture meaning: {DESCRIPTIONS[r['target']]}" text = (f"Write 20 different sentences in {r['language']} that {WHO[r['kind']]}. The speaker is {r['speaker']}; " f"loosely related to {r['topic']}. They should be {what}.\n" "Make them natural spoken language, varied in length (2 to 25 words), wording and situation; avoid starting them " "the same way and avoid clichés. ") if r["asr"]: text += ASR_STYLE return text + "\nAnswer with a JSON list of 20 strings only." def main() -> None: out_path, models, repeats, seed = Path(sys.argv[1]), sys.argv[2].split(","), int(sys.argv[3]), int(sys.argv[4]) fraction = float(sys.argv[5]) if len(sys.argv) > 5 else 1.0 rng = random.Random(seed) todo = [r | {"model": rng.choice(models), "rep": rep} for rep in range(repeats) for kind in ("say", "react") for r in requests(kind, rng)] todo = [r for r in todo if rng.random() < fraction] done = set() if out_path.exists(): done = {json.loads(line)["req"] for line in out_path.open()} for n, r in enumerate(todo): r["req"] = f"{seed}-{n}" todo = [r for r in todo if r["req"] not in done] print(f"{len(todo)} requests to go", flush=True) client = InferenceClient(provider="auto", timeout=240) lock = threading.Lock() def run(r: dict) -> None: for attempt in range(3): try: resp = client.chat_completion(model=r["model"], messages=[{"role": "user", "content": prompt(r)}], max_tokens=16000, temperature=1.0) text = re.sub(r".*?", "", resp.choices[0].message.content or "", flags=re.S) items = json.loads(re.search(r"\[.*\]", text, flags=re.S).group(0)) sentences = [s.strip() for s in items if isinstance(s, str) and 1 < len(s.strip()) < 300] if len(sentences) >= 10: with lock, out_path.open("a") as f: f.write(json.dumps(r | {"sentences": sentences}, ensure_ascii=False) + "\n") return except Exception as error: # noqa: BLE001 - provider hiccups are retried print(f" {r['model']} {r['req']}: {type(error).__name__}: {str(error)[:120]}", flush=True) print(f" gave up on {r['req']}", flush=True) with ThreadPoolExecutor(16) as pool: list(pool.map(run, todo)) if __name__ == "__main__": main()