Skip to content

Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.

update TTS pipeline

HenryNdubuaku1a15aadae399
diff --git a/scripts/build_dataset.py b/scripts/build_dataset.py
index 19de90b..9a0fdf3 100644
--- a/scripts/build_dataset.py
+++ b/scripts/build_dataset.py
@@ -29,7 +29,9 @@ from tools_data import load_and_combine
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
-VOICES = [
+# Voice templates — defined as Wavenet; the type (Wavenet/Neural2/Standard)
+# is swapped at synthesis time via _get_voice() to spread load across quotas.
+_VOICE_TEMPLATES = [
("en-GB", "en-GB-Wavenet-B", "MALE", True, False),
("en-GB", "en-GB-Wavenet-A", "FEMALE", True, False),
("en-AU", "en-AU-Wavenet-B", "MALE", True, False),
@@ -45,6 +47,26 @@ VOICES = [
("en-IN", "en-IN-Wavenet-A", "FEMALE", True, True),
]
+# Two voice types, each with its own 1k/min quota (2k/min total)
+_VOICE_TYPES = ["Wavenet", "Neural2"]
+
+
+def _get_voice(idx):
+ """Return (lang, voice_name, gender_str, configurable, child) for a sample.
+
+ Cycles through voice types (Wavenet→Neural2→Standard) via idx % 3,
+ then picks a voice template via (idx // 3) % len(_VOICE_TEMPLATES).
+ This distributes requests evenly across the three quota buckets.
+ """
+ vtype = _VOICE_TYPES[idx % len(_VOICE_TYPES)]
+ template = _VOICE_TEMPLATES[(idx // 3) % len(_VOICE_TEMPLATES)]
+ lang, base_name, gender, configurable, child = template
+ voice_name = base_name.replace("Wavenet", vtype)
+ return lang, voice_name, gender, configurable, child
+
+# Keep VOICES as alias for backfill (uses templates only)
+VOICES = _VOICE_TEMPLATES
+
def _pcm_to_wav_bytes(pcm_bytes: bytes, sample_rate: int) -> bytes:
"""Convert raw LINEAR16 PCM bytes to a WAV byte buffer."""
@@ -70,7 +92,7 @@ def _synthesize_one(client, idx, query, max_retries=5):
from google.cloud import texttospeech
from google.api_core.exceptions import ResourceExhausted, ServiceUnavailable
- lang, voice_name, ssml_gender, configurable, child = VOICES[idx % len(VOICES)]
+ lang, voice_name, ssml_gender, configurable, child = _get_voice(idx)
gender = getattr(texttospeech.SsmlVoiceGender, ssml_gender)
synthesis_input = texttospeech.SynthesisInput(text=query)
@@ -127,9 +149,12 @@ def _load_text_dataset(output_path, max_samples):
"""
existing_ds = None
if os.path.exists(output_path):
- logger.info(f"Found existing dataset at {output_path}, loading for resume...")
- existing_ds = load_from_disk(output_path)
- logger.info(f" Existing dataset: {len(existing_ds)} rows")
+ try:
+ logger.info(f"Found existing dataset at {output_path}, loading for resume...")
+ existing_ds = load_from_disk(output_path)
+ logger.info(f" Existing dataset: {len(existing_ds)} rows")
+ except (FileNotFoundError, Exception) as e:
+ logger.warning(f"Could not load existing dataset (will use audio cache only): {e}")
logger.info("Loading and combining text datasets...")
combined = load_and_combine()
@@ -244,25 +269,50 @@ def _synthesize_missing(combined, needs_tts, audio_data, voice_names, workers, r
success, failed = 0, 0
delay = 1.0 / rate_limit if rate_limit > 0 else 0
+ total = len(queries_to_synth)
+
with ThreadPoolExecutor(max_workers=workers) as pool:
- futures = {}
- for q in queries_to_synth:
- futures[pool.submit(_worker, q)] = q
- time.sleep(delay)
- with tqdm(total=len(futures), desc="TTS") as pbar:
- for future in as_completed(futures):
- idx, wav_bytes, voice_name, err = future.result()
- if wav_bytes is not None:
- wav_path = os.path.join(cache_dir, f"{idx}.wav")
- with open(wav_path, "wb") as f:
- f.write(wav_bytes)
- audio_data[idx] = wav_path
- voice_names[idx] = voice_name
- success += 1
- else:
- failed += 1
- logger.warning(f"Failed idx={idx}: {err}")
- pbar.update(1)
+ pending = {}
+ submitted = 0
+ qi = iter(queries_to_synth)
+
+ # Seed the pool with initial batch
+ for _ in range(min(workers * 2, total)):
+ q = next(qi)
+ pending[pool.submit(_worker, q)] = q
+ submitted += 1
+
+ with tqdm(total=total, desc="TTS") as pbar:
+ while pending:
+ done_set = set()
+ for fut in list(pending):
+ if fut.done():
+ done_set.add(fut)
+ if not done_set:
+ # Wait for at least one to finish
+ time.sleep(0.05)
+ continue
+ for fut in done_set:
+ idx, wav_bytes, voice_name, err = fut.result()
+ if wav_bytes is not None:
+ wav_path = os.path.join(cache_dir, f"{idx}.wav")
+ with open(wav_path, "wb") as f:
+ f.write(wav_bytes)
+ audio_data[idx] = wav_path
+ voice_names[idx] = voice_name
+ success += 1
+ else:
+ failed += 1
+ logger.warning(f"Failed idx={idx}: {err}")
+ pbar.update(1)
+ del pending[fut]
+
+ # Submit new work to maintain pool pressure
+ if submitted < total:
+ q = next(qi)
+ pending[pool.submit(_worker, q)] = q
+ submitted += 1
+ time.sleep(delay)
logger.info(f"TTS done: {success} generated, {failed} failed")
@@ -333,10 +383,10 @@ def main():
"""Entry point for the unified dataset build pipeline."""
parser = argparse.ArgumentParser(description="Build unified tool-call dataset with TTS audio")
parser.add_argument("--max-samples", type=int, default=None, help="Max samples to process")
- parser.add_argument("--workers", type=int, default=8, help="TTS concurrent workers (default: 8)")
+ parser.add_argument("--workers", type=int, default=16, help="TTS concurrent workers (default: 16)")
parser.add_argument("--output", type=str, default="data/tool_calls_unified", help="Output directory")
- parser.add_argument("--rate-limit", type=float, default=15.0,
- help="Max TTS requests per second (default: 15, quota is 1000/min)")
+ parser.add_argument("--rate-limit", type=float, default=30.0,
+ help="Max TTS requests per second (default: 30, quota is 2x1000/min)")
parser.add_argument("--gcs-upload", type=str, default=None,
help="GCS path to upload dataset (e.g. gs://cactus-dataset/tool_calls)")
args = parser.parse_args()
diff --git a/scripts/tools_data.py b/scripts/tools_data.py
index 8308b9b..0ebff86 100755
--- a/scripts/tools_data.py
+++ b/scripts/tools_data.py
@@ -254,6 +254,85 @@ CONVERTERS = {
"ToolACE": convert_toolace,
}
+_PLACEHOLDER_VALUES = {
+ "john_doe", "jane_doe", "john.doe", "jane.doe",
+ "john_doe_456", "jane_doe_123",
+ "1234567890", "0987654321",
+ "123 main st", "123 main street",
+}
+
+
+def _has_placeholder_args(answers_json):
+ """Check if any argument values are known placeholders."""
+ try:
+ answers = json.loads(answers_json)
+ except (json.JSONDecodeError, TypeError):
+ return False
+ if not answers:
+ return False
+ for call in answers:
+ args = call.get("arguments", {})
+ if isinstance(args, str):
+ try:
+ args = json.loads(args)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ if not isinstance(args, dict):
+ continue
+ for val in args.values():
+ if isinstance(val, str) and val.lower().strip() in _PLACEHOLDER_VALUES:
+ return True
+ return False
+
+
+def _answer_grounded(query, answers_json):
+ """Check that at least one non-trivial argument value appears in the query.
+
+ For examples with function calls, this catches cases where the answer
+ contains hallucinated arguments that have nothing to do with the query.
+ Skips examples with no answers (no-call examples) — those are always kept.
+ Also skips examples where all arguments are booleans/numbers/short enums,
+ since those don't need to be grounded in the query text.
+ """
+ try:
+ answers = json.loads(answers_json)
+ except (json.JSONDecodeError, TypeError):
+ return True
+ if not answers:
+ return True
+
+ query_lower = query.lower()
+ has_string_arg = False
+
+ for call in answers:
+ args = call.get("arguments", {})
+ if isinstance(args, str):
+ try:
+ args = json.loads(args)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ if not isinstance(args, dict):
+ continue
+ for val in args.values():
+ if isinstance(val, str) and len(val) >= 3:
+ has_string_arg = True
+ val_lower = val.lower().strip()
+ if val_lower in query_lower:
+ return True
+ val_words = val_lower.split()
+ if len(val_words) > 1:
+ matches = sum(1 for w in val_words if len(w) >= 3 and w in query_lower)
+ if matches >= len(val_words) * 0.5:
+ return True
+
+ if not has_string_arg:
+ return True
+
+ return False
+
def load_and_combine():
parts = []
@@ -268,12 +347,21 @@ def load_and_combine():
print(f" Converting to xlam format...")
converted = CONVERTERS[name](ds["train"])
converted = converted.add_column("source", [name] * len(converted))
+
+ before = len(converted)
+ converted = converted.filter(
+ lambda ex: not _has_placeholder_args(ex["answers"]) and _answer_grounded(ex["query"], ex["answers"]),
+ desc=f"Filtering {name}",
+ )
+ dropped = before - len(converted)
+ if dropped:
+ print(f" Filtered out {dropped} low-quality examples ({dropped*100/before:.1f}%)")
+
print(f" -> {len(converted)} examples")
parts.append(converted)
combined = concatenate_datasets(parts)
- # Compact tool schemas: strip descriptions, keep only name + param name/type
print(f"\nCompacting tool schemas...")
combined = combined.map(
lambda ex: {"tools": compact_tools(ex["tools"])},