Text Generation
Transformers
Safetensors
English
speech
duplex
voice-assistant
streaming
tool-calling
qwen
text-to-speech
Instructions to use sadmN/aiden-duplex with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use sadmN/aiden-duplex with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="sadmN/aiden-duplex")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("sadmN/aiden-duplex", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use sadmN/aiden-duplex with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "sadmN/aiden-duplex" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/sadmN/aiden-duplex
- SGLang
How to use sadmN/aiden-duplex with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "sadmN/aiden-duplex" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "sadmN/aiden-duplex" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use sadmN/aiden-duplex with Docker Model Runner:
docker model run hf.co/sadmN/aiden-duplex
Download code/duplex/voice_worker.py from sadmN/aiden-duplex: direct link, hf CLI and curl.
- Browser
- Download file 9.58 kB
-
https://huggingface.co/sadmN/aiden-duplex/resolve/main/code/duplex/voice_worker.py
- Command line
-
hf download hf://sadmN/aiden-duplex/code/duplex/voice_worker.py
-
curl -L -o voice_worker.py https://huggingface.co/sadmN/aiden-duplex/resolve/main/code/duplex/voice_worker.py
9.58 kB
| """Voice worker: Aiden TTS + ASR with per-word causal prosody (codec_bench/env). | |
| JSONL protocol on stdin/stdout. | |
| TTS in : {"op":"tts","id":3,"text":"Sure, let me check."} | |
| out: {"id":3,"sr":24000,"ms":412,"dur":1.8,"audio_b64":"<wav>"} | |
| ASR in : {"op":"asr","id":4,"wav_b64":"<16k mono wav>"} | |
| out: {"id":4,"text":"check the weather in berlin", | |
| "words":[{"w":"check","t0":0.12,"t1":0.41,"vec_b64":"<512 f16>"}], "ms":310} | |
| The words carry the pooled causal Mimi vector over exactly the span the trainer uses | |
| (word_start-0.08 .. word_end+0.16). That is what lets a live voice turn use the same | |
| PROSODY-marker prompt shape as training instead of a clean-text fallback. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import base64 | |
| import io | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| TTS_MODEL = os.environ.get('AIDEN_TTS_MODEL', | |
| '/workspace/chroma_duplex_demo/models/qwen3_tts_1.7b_customvoice') | |
| ASR_PATH = os.environ.get('AIDEN_ASR_MODEL', | |
| '/workspace/speech_comparison/models/asr_evaluation/' | |
| 'models--mobiuslabsgmbh--faster-whisper-large-v3-turbo/' | |
| 'snapshots/0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf') | |
| MIMI_CKPT = os.environ.get('AIDEN_MIMI', | |
| '/workspace/speech_comparison/models/personaplex/' | |
| 'tokenizer-e351c8d8-checkpoint125.safetensors') | |
| MOSHI_SRC = os.environ.get('AIDEN_MOSHI_SRC', | |
| '/workspace/speech_comparison/src/personaplex') | |
| SR = 24000 | |
| FRAME_RATE = 12.5 | |
| MIMI_CHUNK = 1920 * 10 | |
| INSTRUCT = ('Lively, warm, conversational American English. Natural pacing, ' | |
| 'a slight smile in the voice, clear articulation.') | |
| def wav_bytes(w, sr): | |
| buf = io.BytesIO() | |
| sf.write(buf, np.asarray(w, dtype=np.float32).reshape(-1), sr, | |
| format='WAV', subtype='PCM_16') | |
| return buf.getvalue() | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('lane', choices=('tts', 'input')) | |
| args = parser.parse_args() | |
| t0 = time.time() | |
| if args.lane == 'tts': | |
| from qwen_tts import Qwen3TTSModel | |
| tts = Qwen3TTSModel.from_pretrained(TTS_MODEL, device_map='cuda:0', | |
| dtype=torch.bfloat16, | |
| attn_implementation='sdpa', local_files_only=True) | |
| else: | |
| from faster_whisper import WhisperModel | |
| asr = WhisperModel(ASR_PATH, device='cuda', compute_type='float16') | |
| sys.path.insert(0, MOSHI_SRC) | |
| from moshi.models.loaders import get_mimi | |
| mimi = get_mimi(Path(MIMI_CKPT), device='cuda') | |
| mimi.set_num_codebooks(8) | |
| mimi.eval() | |
| def synthesize(text): | |
| return tts.generate_custom_voice(text=text, language='English', speaker='Aiden', | |
| instruct=INSTRUCT, max_new_tokens=256, | |
| do_sample=False) | |
| def synth_batch(texts): | |
| n = len(texts) | |
| return tts.generate_custom_voice(text=list(texts), language='English', | |
| speaker=['Aiden'] * n, | |
| instruct=[INSTRUCT] * n, | |
| max_new_tokens=256, do_sample=False) | |
| def prosody(x16): | |
| """Causal Mimi latents for a finished utterance -> (frames, n).""" | |
| import librosa | |
| x24 = librosa.resample(x16, orig_sr=16000, target_sr=SR, res_type='soxr_hq') | |
| x24 = np.ascontiguousarray(x24, dtype=np.float32) | |
| try: | |
| mimi.reset_streaming() | |
| except ValueError: | |
| pass | |
| mimi.streaming_forever(1) | |
| outs = [] | |
| for i in range(0, len(x24), MIMI_CHUNK): | |
| c = x24[i:i + MIMI_CHUNK] | |
| if len(c) < MIMI_CHUNK: | |
| c = np.pad(c, (0, MIMI_CHUNK - len(c))) | |
| outs.append(mimi.encode_to_latent( | |
| torch.from_numpy(np.ascontiguousarray(c))[None, None].cuda(), | |
| quantize=False)[0].float().cpu()) | |
| try: | |
| mimi.reset_streaming() | |
| except ValueError: | |
| pass | |
| lat = torch.cat(outs, dim=-1) | |
| keep = int(len(x16) // 1280) # only complete 80 ms frames | |
| return lat[:, :keep].numpy() | |
| if args.lane == 'tts': | |
| synthesize('Hello.') | |
| else: | |
| silence = np.zeros(8000, dtype=np.float32) | |
| list(asr.transcribe(silence, beam_size=1, language='en', word_timestamps=True)[0]) | |
| prosody(silence) | |
| print(json.dumps({'ready': True, 'lane': args.lane, | |
| 'warm_s': round(time.time() - t0, 2)}), flush=True) | |
| def vector(lat): | |
| return base64.b64encode(lat.mean(axis=1).astype(np.float16).tobytes()).decode() | |
| for line in sys.stdin: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| req = json.loads(line) | |
| except ValueError: | |
| continue | |
| op, rid = req.get('op'), req.get('id') | |
| t0 = time.time() | |
| try: | |
| if args.lane == 'tts' and op == 'tts': | |
| texts = req.get('texts') | |
| if texts is None: | |
| texts = [req.get('text') or ''] | |
| texts = [t.strip() for t in texts if t and t.strip()] | |
| if not texts: | |
| print(json.dumps({'id': rid, 'error': 'empty'}), flush=True) | |
| continue | |
| # One batched call: the model is slow per sentence (~1x real time), | |
| # so batching is what lets audio arrive ahead of playback. | |
| try: | |
| if len(texts) == 1: | |
| # single-clause path is ~2x faster than the list API | |
| wavs, sr = synthesize(texts[0]) | |
| else: | |
| wavs, sr = synth_batch(texts) | |
| except Exception: | |
| wavs, sr = [synthesize(t)[0][0] for t in texts], SR | |
| audios = [] | |
| for w in wavs: | |
| w = np.asarray(w, dtype=np.float32).reshape(-1) | |
| if sr != SR: | |
| import torchaudio | |
| w = torchaudio.functional.resample( | |
| torch.from_numpy(w), sr, SR).numpy() | |
| audios.append({'dur': round(len(w) / SR, 3), | |
| 'audio_b64': base64.b64encode(wav_bytes(w, SR)).decode()}) | |
| out = {'id': rid, 'sr': SR, 'audios': audios, | |
| 'ms': round((time.time() - t0) * 1000, 1)} | |
| if len(audios) == 1: | |
| out.update(audio_b64=audios[0]['audio_b64'], dur=audios[0]['dur']) | |
| print(json.dumps(out), flush=True) | |
| elif args.lane == 'input' and op in ('asr', 'onset', 'partial'): | |
| raw = base64.b64decode(req.get('wav_b64') or '') | |
| w, sr = sf.read(io.BytesIO(raw), dtype='float32', always_2d=True) | |
| mono = w.mean(axis=1) if w.shape[1] > 1 else w[:, 0] | |
| if sr != 16000: | |
| import librosa | |
| mono = librosa.resample(mono, orig_sr=sr, target_sr=16000) | |
| mono = np.ascontiguousarray(mono, dtype=np.float32) | |
| if op == 'onset': | |
| lat = prosody(mono) | |
| print(json.dumps({'id': rid, 'vec': vector(lat) if lat.shape[1] else None}), | |
| flush=True) | |
| continue | |
| segs, _ = asr.transcribe(mono, beam_size=1, language='en', | |
| vad_filter=False, | |
| condition_on_previous_text=False, | |
| word_timestamps=op == 'asr') | |
| if op == 'partial': | |
| text = ' '.join(s.text.strip() for s in segs if s.no_speech_prob < .6) | |
| print(json.dumps({'id': rid, 'text': text, | |
| 'ms': round((time.time() - t0) * 1000, 1)}), flush=True) | |
| continue | |
| words, pieces = [], [] | |
| for s in segs: | |
| for wd in s.words or []: | |
| txt = (wd.word or '').strip() | |
| if txt: | |
| pieces.append(txt) | |
| words.append({'w': txt, 't0': float(wd.start), | |
| 't1': float(wd.end)}) | |
| text = ' '.join(pieces) | |
| if words: | |
| lat = prosody(mono) | |
| nf = lat.shape[1] | |
| for wd in words: | |
| f0 = max(0, int((wd['t0'] - 0.08) * FRAME_RATE)) | |
| f1 = min(nf, int((wd['t1'] + 0.16) * FRAME_RATE)) | |
| if f1 > f0: | |
| wd['vec_b64'] = vector(lat[:, f0:f1]) | |
| print(json.dumps({'id': rid, 'text': text, 'words': words, | |
| 'ms': round((time.time() - t0) * 1000, 1)}), flush=True) | |
| elif op == 'ping': | |
| print(json.dumps({'pong': True}), flush=True) | |
| else: | |
| print(json.dumps({'id': rid, 'error': f'unknown op {op}'}), flush=True) | |
| except Exception as exc: | |
| print(json.dumps({'id': rid, 'error': repr(exc)[:400]}), flush=True) | |
| if __name__ == '__main__': | |
| main() | |