#!/usr/bin/env python3 """Azemari inference — Amharic, Afaan Oromoo, Tigrinya TTS with voice cloning. Requires the public IndexTTS-2.5 codebase with the Azemari patch applied (see install_kaggle.sh in this repo). Everything needed for inference is in the model directory; only w2v-bert-2.0, CAMPPlus and BigVGAN are fetched once into /hf_cache on first run. Single line: python infer_azemari.py --model-dir ./azemari --ref voice.wav \ --text "ሰላም፣ እንዴት ነህ?" --lang am --emotion calm --out line.wav Full script (JSONL, one object per line: {"text": "...", "out": "a.wav", "emotion": "sad"}): python infer_azemari.py --model-dir ./azemari --ref voice.wav --script lines.jsonl """ from __future__ import annotations import argparse import json import os import sys import time from pathlib import Path EMOTIONS = ["happy", "angry", "sad", "afraid", "disgusted", "melancholic", "surprised", "calm"] LANGS = ("am", "om", "ti") def parse_emotion(value: str | None) -> list[float] | None: """'calm' -> one-hot vector; '0,0,0,0,0,0,0,1' -> explicit vector.""" if not value: return None if "," in value: vec = [float(x) for x in value.split(",")] if len(vec) != len(EMOTIONS): raise SystemExit(f"emotion vector needs {len(EMOTIONS)} values, got {len(vec)}") return vec if value not in EMOTIONS: raise SystemExit(f"unknown emotion {value!r}; choose from {', '.join(EMOTIONS)}") return [1.0 if name == value else 0.0 for name in EMOTIONS] def check_patch() -> None: """Fail early with a useful message if the Azemari patch is not applied.""" try: from indextts.utils.tokenizer import LANGUAGE_DICT except ModuleNotFoundError as exc: raise SystemExit( "The public IndexTTS-2.5 codebase is not importable. Run install_kaggle.sh, " "or pip install -e . from the index-tts checkout.\n" + str(exc) ) from exc missing = [lang for lang in LANGS if lang not in LANGUAGE_DICT] if missing: raise SystemExit( "Azemari tokenizer patch missing for: " + ", ".join(missing) + "\nCopy tokenizer_ethiopic.py over indextts/utils/tokenizer.py (install_kaggle.sh does this)." ) def build_tts(model_dir: str, device: str | None, use_bf16: bool, qwen_emo: bool): from indextts.infer_v2_5 import IndexTTS2 cfg = os.path.join(model_dir, "config.yaml") if not os.path.isfile(cfg): raise SystemExit(f"config.yaml not found in {model_dir} — point --model-dir at the hf download of Lab-et/azemari") tts = IndexTTS2(cfg_path=cfg, model_dir=model_dir, use_bf16=use_bf16, device=device, use_qwen_emo=qwen_emo) return tts def generate(tts, ref: str, text: str, out: str, lang: str, emo: list[float] | None, emo_audio: str | None, emo_alpha: float, interval_silence: int, max_tokens: int, duration_factor: float, verbose: bool) -> float: Path(out).parent.mkdir(parents=True, exist_ok=True) t0 = time.time() tts.infer( spk_audio_prompt=ref, text=text, output_path=out, lang=lang, emo_vector=emo, emo_audio_prompt=emo_audio, emo_alpha=emo_alpha, interval_silence=interval_silence, max_text_tokens_per_segment=max_tokens, duration_factor=duration_factor, verbose=verbose, ) return time.time() - t0 def main() -> int: ap = argparse.ArgumentParser(description="Azemari TTS inference") ap.add_argument("--model-dir", default="azemari", help="path to the Lab-et/azemari download") ap.add_argument("--ref", required=True, help="reference voice clip, 10-20 s, clean, one speaker") ap.add_argument("--text") ap.add_argument("--out") ap.add_argument("--script", help="JSONL with {text, out, lang?, emotion?} per line") ap.add_argument("--lang", default="am", choices=list(LANGS)) ap.add_argument("--emotion", help="name (" + ", ".join(EMOTIONS) + ") or 8 comma-separated weights") ap.add_argument("--emo-audio", help="acted reference clip for emotion transfer (overrides --emotion)") ap.add_argument("--emo-alpha", type=float, default=1.0, help="emotion strength multiplier") ap.add_argument("--interval-silence", type=int, default=200, help="ms of silence between segments") ap.add_argument("--max-text-tokens", type=int, default=120, help="lower if long lines truncate") ap.add_argument("--duration-factor", type=float, default=1.0, help="stretch delivery to fit a cue") ap.add_argument("--device", help="cuda:0, mps, cpu (default: auto)") ap.add_argument("--bf16", action="store_true", help="bfloat16 on supported GPUs") ap.add_argument("--qwen-emo", action="store_true", help="load QwenEmotion for emo_text") ap.add_argument("--verbose", action="store_true") args = ap.parse_args() if not os.path.isfile(args.ref): raise SystemExit(f"reference audio not found: {args.ref}") if not args.script and not (args.text and args.out): raise SystemExit("provide --text and --out, or --script") check_patch() tts = build_tts(args.model_dir, args.device, args.bf16, args.qwen_emo) jobs = [] if args.script: with open(args.script, encoding="utf-8") as fh: for i, line in enumerate(fh, 1): line = line.strip() if not line: continue row = json.loads(line) jobs.append({ "text": row["text"], "out": row.get("out") or f"line_{i:04d}.wav", "lang": row.get("lang", args.lang), "emotion": row.get("emotion", args.emotion), }) else: jobs.append({"text": args.text, "out": args.out, "lang": args.lang, "emotion": args.emotion}) for job in jobs: emo = parse_emotion(job["emotion"]) took = generate(tts, args.ref, job["text"], job["out"], job["lang"], emo, args.emo_audio, args.emo_alpha, args.interval_silence, args.max_text_tokens, args.duration_factor, args.verbose) print(f"[{job['lang']}] {job['out']} {took:.1f}s {job['text'][:60]}") return 0 if __name__ == "__main__": sys.exit(main())