| """ |
| Build AMD dataset v3: Mix real human speech + TTS-generated samples. |
| |
| Real speech sources: |
| - PolyAI/minds14 (en-US, en-GB, en-AU): Real callers to phone banking IVR |
| - MLCommons/peoples_speech (clean subset): Diverse conversational English |
| |
| Strategy: |
| - human: ~200 real (MINDS14+peoples_speech) + ~200 TTS = 400 total |
| - voicemail: 400 TTS (voicemail content IS typically human-recorded, TTS voices + beep) |
| - ivr: 400 TTS (IVR systems ARE synthetic — TTS is realistic for this class) |
| - answering_machine: 400 TTS (carrier messages ARE automated — TTS is realistic) |
| |
| This ensures the model can't shortcut by detecting "TTS signature = not human" |
| since TTS appears in ALL classes, and real speech appears in the human class. |
| """ |
|
|
| import asyncio |
| import edge_tts |
| import numpy as np |
| import soundfile as sf |
| import os |
| import sys |
| import random |
| from pydub import AudioSegment |
| from scipy.signal import butter, lfilter |
| from datasets import load_dataset, Audio, Dataset, ClassLabel |
|
|
| random.seed(42) |
| np.random.seed(42) |
| sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1) |
|
|
| SAMPLE_RATE = 16000 |
| MAX_LENGTH_S = 10.0 |
| OUTPUT_DIR = "/app/amd_dataset_v3" |
| audio_dir = os.path.join(OUTPUT_DIR, "audio") |
| os.makedirs(audio_dir, exist_ok=True) |
|
|
| LABELS = ["human", "voicemail", "ivr", "answering_machine"] |
|
|
| |
| NAMES = ["John", "Sarah", "Mike", "Emily", "David", "Lisa", "James", "Anna", |
| "Robert", "Jessica", "Chris", "Rachel", "Tom", "Maria", "Steve", "Amy", |
| "Kevin", "Sophia", "Daniel", "Nicole", "Mark", "Laura", "Brian", "Megan"] |
| COMPANIES = ["Acme Corp", "Global Services", "Tech Solutions", "First National Bank", |
| "City Medical Center", "Pacific Insurance", "Metro Legal", "Summit Realty", |
| "Valley Dental", "Premier Auto", "Coastal Roofing", "Downtown Pizza"] |
|
|
| |
| HUMAN_TEMPLATES = [ |
| "Hello?", "Hi there.", "Yeah?", "Hello, who's calling?", |
| "Hi, this is {name} speaking.", "Hello, {name} here.", |
| "Yeah hi, who is this?", "Hello, how can I help you?", |
| "Hi, what can I do for you?", "Hey, what's up?", |
| "Hello? Can you hear me?", "Yeah, go ahead.", |
| "Hello, {name} speaking, how can I help?", |
| "Good morning, this is {name}.", "Good afternoon, how may I direct your call?", |
| "Hey, sorry I was just about to call you back.", |
| "Hello? Oh hi, yes this is {name}.", "Yeah I'm here, go ahead.", |
| "Hi, sorry about that, I'm here now.", "Hello, {company}, {name} speaking.", |
| "Good morning, {company}, how can I help you today?", |
| "Yes, speaking.", "This is {name}, who am I speaking with?", |
| "Hello? Hold on one second please.", "Yeah hi, sorry I was in a meeting.", |
| "Hi, thanks for calling back.", "Hello, yes I can talk right now.", |
| "Sure, what do you need?", "Hi, is this about the appointment?", |
| "Hello, what time works for you?", "Yeah, let me check on that for you.", |
| "OK sure, I can help with that.", |
| "Hello? Sorry, bad connection. Can you repeat that?", |
| "Hey yeah, one moment please.", "Hi, I was expecting your call.", |
| ] |
|
|
| VOICEMAIL_TEMPLATES = [ |
| "Hi, you've reached {name}. I'm not available right now. Please leave a message after the beep.", |
| "Hey, it's {name}. I can't come to the phone right now. Leave me a message and I'll call you back.", |
| "You've reached {name} at {company}. I'm away from my desk. Please leave your name, number, and a brief message.", |
| "Hi, this is {name}. Sorry I missed your call. Please leave a message and I'll get back to you as soon as possible.", |
| "Hello, you've reached the voicemail of {name}. I'm unable to take your call right now. Please leave a message.", |
| "Hi, you've reached {name}. I'm either on another call or away from my phone. Please leave a detailed message.", |
| "Hey, this is {name}'s phone. I can't answer right now. Leave a message after the tone.", |
| "You've reached {name}. I'm out of the office right now. Leave a message or try again later.", |
| "Hi, this is {name} with {company}. I'm not available to take your call. Please leave a message.", |
| "Hello, you've reached {name}'s voicemail. Please leave your name and number and I'll return your call.", |
| "Hi, it's {name}. I'm currently unavailable. Please leave a message after the beep and I'll get back to you.", |
| "You've reached {name} at {company}. Our office hours are Monday through Friday, 9 to 5. Please leave a message.", |
| "Hello, this is {name}. I'm not able to answer the phone right now. Your call is important to me. Please leave a message.", |
| "Hey, you've reached {name}. Sorry I couldn't pick up. Drop me a message and I'll hit you back.", |
| "Hi, this is the voicemail of {name}. Leave a message at the beep.", |
| "You've reached {name}. I'm probably busy or in a meeting. Leave a message after the tone.", |
| "Hello, you've reached {name}'s phone. I can't take your call right now. Please leave a message after the beep.", |
| "Hi there, this is {name}. I'm currently away but your call is important to me. Please leave a message.", |
| ] |
|
|
| IVR_TEMPLATES = [ |
| "Thank you for calling {company}. Press 1 for sales, press 2 for support, or press 0 for the operator.", |
| "Welcome to {company}. For English, press 1. Para español, oprima el 2.", |
| "Thank you for calling. Please listen carefully as our menu options have changed.", |
| "Press 1 for billing inquiries. Press 2 for technical support. Press 3 for new accounts.", |
| "Your call is important to us. Please stay on the line and your call will be answered in the order it was received.", |
| "Thank you for calling {company}. Our business hours are Monday through Friday, 8 AM to 6 PM.", |
| "Welcome. For account information, press 1. To make a payment, press 2. To report a problem, press 3.", |
| "Thank you for calling {company} customer service. If you know your party's extension, you may dial it at any time.", |
| "Hello, and thank you for calling {company}. Your call may be recorded for quality assurance purposes.", |
| "Please hold while we transfer your call. Your estimated wait time is 5 minutes.", |
| "All of our representatives are currently busy. Please continue to hold or press 1 to leave a callback number.", |
| "For billing and payments, press 1. For appointments, press 2. For prescription refills, press 3. For all other inquiries, press 4.", |
| "Welcome to {company} automated phone system. Please say the name of the person or department you are trying to reach.", |
| "This call may be monitored or recorded for training purposes. Press 1 to continue.", |
| "Thank you for calling. To access your account, please enter your account number followed by the pound sign.", |
| "Welcome to {company}. For hours and locations, press 1. For customer service, press 2. To hear this menu again, press 9.", |
| ] |
|
|
| AM_TEMPLATES = [ |
| "The person you are calling is not available. Please leave a message after the tone.", |
| "The number you have dialed is not in service. Please check the number and dial again.", |
| "The mailbox is full. Please try your call again later.", |
| "The subscriber you have dialed is not available. At the tone, please record your message.", |
| "This is an automated message. The person you are trying to reach is unavailable.", |
| "Your call has been forwarded to an automated voice messaging system. Please leave a message after the tone.", |
| "The wireless customer you are calling is not available. Please leave a message.", |
| "We're sorry, but the person you called has a voice mailbox that has not been set up yet.", |
| "The number you have reached is not in service at this time.", |
| "At the tone, please record your message. When you are finished, hang up or press 1 for more options.", |
| "Your call cannot be completed as dialed. Please check the number and dial again.", |
| "The Google subscriber you have called is not available. Please leave your message after the tone.", |
| ] |
|
|
| |
| HUMAN_VOICES = [ |
| ("en-US-AvaNeural", "+5%", "+5Hz"), ("en-US-AndrewNeural", "+0%", "+0Hz"), |
| ("en-US-EmmaNeural", "+8%", "+10Hz"), ("en-US-BrianNeural", "+5%", "+5Hz"), |
| ("en-GB-SoniaNeural", "+0%", "+0Hz"), ("en-US-JennyNeural", "+3%", "+5Hz"), |
| ("en-US-GuyNeural", "+5%", "+0Hz"), ("en-GB-RyanNeural", "+0%", "+0Hz"), |
| ("en-AU-NatashaNeural", "+5%", "+5Hz"), ("en-AU-WilliamNeural", "+0%", "+0Hz"), |
| ] |
| VOICEMAIL_VOICES = [ |
| ("en-US-JennyNeural", "-5%", "+0Hz"), ("en-US-AndrewNeural", "-5%", "-10Hz"), |
| ("en-US-MichelleNeural", "-8%", "+0Hz"), ("en-US-EricNeural", "-5%", "+0Hz"), |
| ("en-US-AvaNeural", "-3%", "+0Hz"), ("en-GB-SoniaNeural", "-5%", "+0Hz"), |
| ("en-AU-NatashaNeural", "-5%", "+0Hz"), ("en-US-BrianNeural", "-5%", "-5Hz"), |
| ] |
| IVR_VOICES = [ |
| ("en-US-ChristopherNeural", "-20%", "-50Hz"), ("en-US-GuyNeural", "-20%", "-40Hz"), |
| ("en-US-SteffanNeural", "-25%", "-60Hz"), ("en-US-AriaNeural", "-20%", "-30Hz"), |
| ("en-GB-RyanNeural", "-20%", "-40Hz"), ("en-US-EricNeural", "-15%", "-30Hz"), |
| ] |
| AM_VOICES = [ |
| ("en-US-GuyNeural", "-15%", "-20Hz"), ("en-US-RogerNeural", "-10%", "-15Hz"), |
| ("en-US-ChristopherNeural", "-15%", "-25Hz"), ("en-US-SteffanNeural", "-20%", "-40Hz"), |
| ] |
|
|
| |
| def telephone_bandpass(audio, sr=16000, lowcut=300, highcut=3400): |
| nyq = sr / 2 |
| b, a = butter(4, [lowcut / nyq, min(highcut / nyq, 0.99)], btype='band') |
| return lfilter(b, a, audio).astype(np.float32) |
|
|
| def add_noise(audio, snr_db=25): |
| p = np.mean(audio ** 2) + 1e-10 |
| return (audio + np.random.normal(0, np.sqrt(p / (10 ** (snr_db / 10))), len(audio))).astype(np.float32) |
|
|
| def generate_tone(freq, dur, sr=16000, amp=0.3): |
| t = np.arange(int(dur * sr)) / sr |
| return (amp * np.sin(2 * np.pi * freq * t)).astype(np.float32) |
|
|
| def generate_dtmf(digit, dur=0.15, sr=16000, amp=0.15): |
| dtmf = {'1':(697,1209),'2':(697,1336),'3':(697,1477),'4':(770,1209), |
| '5':(770,1336),'6':(770,1477),'7':(852,1209),'8':(852,1336), |
| '9':(852,1477),'0':(941,1336)} |
| f1, f2 = dtmf.get(digit, (697, 1209)) |
| t = np.arange(int(dur * sr)) / sr |
| return (amp * (np.sin(2*np.pi*f1*t) + np.sin(2*np.pi*f2*t))).astype(np.float32) |
|
|
| def silence(dur, sr=16000): |
| return np.random.normal(0, 0.001, int(dur * sr)).astype(np.float32) |
|
|
| def telephony_fx(audio, sr=16000): |
| audio = telephone_bandpass(audio, sr) |
| audio = add_noise(audio, snr_db=np.random.uniform(18, 35)) |
| audio = audio * np.random.uniform(0.6, 1.3) |
| return np.clip(audio, -1, 1).astype(np.float32) |
|
|
| def load_mp3_wav(path, sr=16000): |
| a = AudioSegment.from_mp3(path).set_frame_rate(sr).set_channels(1).set_sample_width(2) |
| return np.array(a.get_array_of_samples(), dtype=np.float32) / 32768.0 |
|
|
| def fill(t): |
| return t.format(name=random.choice(NAMES), company=random.choice(COMPANIES)) |
|
|
| |
| def decode_audio_bytes(audio_bytes, target_sr=16000): |
| """Decode audio bytes using ffmpeg binary (works without system ffmpeg libs).""" |
| import subprocess |
| proc = subprocess.run( |
| ['ffmpeg', '-i', 'pipe:0', '-f', 's16le', '-ar', str(target_sr), '-ac', '1', 'pipe:1'], |
| input=audio_bytes, capture_output=True |
| ) |
| if proc.returncode == 0 and len(proc.stdout) > 0: |
| return np.frombuffer(proc.stdout, dtype=np.int16).astype(np.float32) / 32768.0 |
| return None |
|
|
| def load_real_human_speech(n_target=200): |
| """Load real human speech from MINDS14 via direct parquet + ffmpeg decoding.""" |
| from huggingface_hub import hf_hub_download |
| import pyarrow.parquet as pq |
| |
| samples = [] |
| max_s = int(MAX_LENGTH_S * SAMPLE_RATE) |
|
|
| |
| parquet_files = { |
| 'en-US': 'en-US/train-00000-of-00001.parquet', |
| 'en-GB': 'en-GB/train-00000-of-00001.parquet', |
| 'en-AU': 'en-AU/train-00000-of-00001.parquet', |
| } |
| |
| for lang, pq_path in parquet_files.items(): |
| if len(samples) >= n_target: |
| break |
| try: |
| print(f" Loading MINDS14 {lang}...") |
| local = hf_hub_download('PolyAI/minds14', pq_path, repo_type='dataset') |
| table = pq.read_table(local) |
| audio_col = table.column('audio') |
| |
| for i in range(len(audio_col)): |
| if len(samples) >= n_target: |
| break |
| row = audio_col[i].as_py() |
| audio_bytes = row.get('bytes') |
| if not audio_bytes: |
| continue |
| arr = decode_audio_bytes(audio_bytes, SAMPLE_RATE) |
| if arr is None or len(arr) < SAMPLE_RATE: |
| continue |
| if len(arr) > max_s: |
| start = random.randint(0, len(arr) - max_s) |
| arr = arr[start:start + max_s] |
| |
| arr = add_noise(arr, snr_db=np.random.uniform(22, 35)) |
| samples.append(arr) |
| |
| print(f" {lang}: {len(table)} rows available, total so far: {len(samples)}") |
| except Exception as e: |
| print(f" {lang} failed: {e}") |
|
|
| print(f" Total real human speech: {len(samples)}") |
| return samples[:n_target] |
|
|
| |
| async def gen_tts(text, voice, rate, pitch, wav_path): |
| mp3 = wav_path.replace('.wav', '.mp3') |
| await edge_tts.Communicate(text, voice=voice, rate=rate, pitch=pitch).save(mp3) |
| audio = load_mp3_wav(mp3, SAMPLE_RATE) |
| max_s = int(MAX_LENGTH_S * SAMPLE_RATE) |
| audio = audio[:max_s] if len(audio) > max_s else audio |
| audio = telephony_fx(audio, SAMPLE_RATE) |
| sf.write(wav_path, audio, SAMPLE_RATE) |
| os.remove(mp3) |
| return audio |
|
|
| |
| async def main(): |
| N_REAL_HUMAN = 200 |
| N_TTS_HUMAN = 200 |
| N_VOICEMAIL = 400 |
| N_IVR = 400 |
| N_AM = 400 |
|
|
| all_paths = [] |
| all_labels = [] |
|
|
| |
| print("\n=== HUMAN class ===") |
| print(f"Target: {N_REAL_HUMAN} real + {N_TTS_HUMAN} TTS = {N_REAL_HUMAN + N_TTS_HUMAN}") |
|
|
| real_samples = load_real_human_speech(N_REAL_HUMAN) |
| for i, arr in enumerate(real_samples): |
| p = os.path.join(audio_dir, f"human_real_{i:05d}.wav") |
| sf.write(p, arr, SAMPLE_RATE) |
| all_paths.append(p) |
| all_labels.append(0) |
| print(f" Saved {len(real_samples)} real human samples") |
|
|
| print(f" Generating {N_TTS_HUMAN} TTS human samples...") |
| for i in range(N_TTS_HUMAN): |
| text = fill(random.choice(HUMAN_TEMPLATES)) |
| voice, rate, pitch = random.choice(HUMAN_VOICES) |
| p = os.path.join(audio_dir, f"human_tts_{i:05d}.wav") |
| try: |
| await gen_tts(text, voice, rate, pitch, p) |
| all_paths.append(p) |
| all_labels.append(0) |
| except Exception as e: |
| print(f" human_tts_{i} failed: {e}") |
| if (i + 1) % 50 == 0: |
| print(f" TTS human: {i + 1}/{N_TTS_HUMAN}") |
|
|
| |
| print(f"\n=== VOICEMAIL class ({N_VOICEMAIL} TTS) ===") |
| for i in range(N_VOICEMAIL): |
| text = fill(random.choice(VOICEMAIL_TEMPLATES)) |
| voice, rate, pitch = random.choice(VOICEMAIL_VOICES) |
| p = os.path.join(audio_dir, f"voicemail_{i:05d}.wav") |
| try: |
| await gen_tts(text, voice, rate, pitch, p) |
| |
| audio, sr = sf.read(p) |
| beep_freq = random.choice([440, 480, 620, 880, 1000]) |
| beep = generate_tone(beep_freq, np.random.uniform(0.3, 0.8), sr, 0.35) |
| fade = min(int(0.01 * sr), len(beep) // 4) |
| beep[:fade] *= np.linspace(0, 1, fade) |
| beep[-fade:] *= np.linspace(1, 0, fade) |
| audio = np.concatenate([audio, silence(np.random.uniform(0.3, 0.8), sr), beep, |
| silence(np.random.uniform(0.5, 1.0), sr)]) |
| sf.write(p, audio[:int(MAX_LENGTH_S * sr)], sr) |
| all_paths.append(p) |
| all_labels.append(1) |
| except Exception as e: |
| print(f" voicemail_{i} failed: {e}") |
| if (i + 1) % 50 == 0: |
| print(f" Voicemail: {i + 1}/{N_VOICEMAIL}") |
|
|
| |
| print(f"\n=== IVR class ({N_IVR} TTS) ===") |
| for i in range(N_IVR): |
| text = fill(random.choice(IVR_TEMPLATES)) |
| voice, rate, pitch = random.choice(IVR_VOICES) |
| p = os.path.join(audio_dir, f"ivr_{i:05d}.wav") |
| try: |
| await gen_tts(text, voice, rate, pitch, p) |
| |
| if random.random() < 0.3: |
| audio, sr = sf.read(p) |
| dtmf = generate_dtmf(random.choice(list('1234567890')), 0.15, sr) |
| audio = np.concatenate([audio, silence(np.random.uniform(0.5, 1.5), sr), |
| dtmf, silence(0.3, sr)]) |
| sf.write(p, audio[:int(MAX_LENGTH_S * sr)], sr) |
| all_paths.append(p) |
| all_labels.append(2) |
| except Exception as e: |
| print(f" ivr_{i} failed: {e}") |
| if (i + 1) % 50 == 0: |
| print(f" IVR: {i + 1}/{N_IVR}") |
|
|
| |
| print(f"\n=== ANSWERING MACHINE class ({N_AM} TTS) ===") |
| for i in range(N_AM): |
| text = fill(random.choice(AM_TEMPLATES)) |
| voice, rate, pitch = random.choice(AM_VOICES) |
| p = os.path.join(audio_dir, f"am_{i:05d}.wav") |
| try: |
| await gen_tts(text, voice, rate, pitch, p) |
| |
| audio, sr = sf.read(p) |
| beep_freq = random.choice([1000, 1200, 1400]) |
| beep = generate_tone(beep_freq, np.random.uniform(0.8, 1.5), sr, 0.45) |
| fade = int(0.02 * sr) |
| beep[:fade] *= np.linspace(0, 1, fade) |
| beep[-fade:] *= np.linspace(1, 0, fade) |
| audio = np.concatenate([audio, silence(np.random.uniform(0.2, 0.5), sr), |
| beep, silence(np.random.uniform(1.0, 2.0), sr)]) |
| sf.write(p, audio[:int(MAX_LENGTH_S * sr)], sr) |
| all_paths.append(p) |
| all_labels.append(3) |
| except Exception as e: |
| print(f" am_{i} failed: {e}") |
| if (i + 1) % 50 == 0: |
| print(f" AM: {i + 1}/{N_AM}") |
|
|
| |
| print(f"\n=== Building dataset: {len(all_paths)} samples ===") |
| for i, name in enumerate(LABELS): |
| c = sum(1 for l in all_labels if l == i) |
| print(f" {name}: {c}") |
|
|
| dataset = Dataset.from_dict({"audio": all_paths, "label": all_labels}) |
| dataset = dataset.cast_column("audio", Audio(sampling_rate=SAMPLE_RATE)) |
| dataset = dataset.cast_column("label", ClassLabel(names=LABELS)) |
| dataset = dataset.shuffle(seed=42) |
| splits = dataset.train_test_split(test_size=0.15, seed=42, stratify_by_column="label") |
|
|
| print(f"\nTrain: {len(splits['train'])}, Test: {len(splits['test'])}") |
| for s in ['train', 'test']: |
| for i, name in enumerate(LABELS): |
| print(f" {s}/{name}: {splits[s]['label'].count(i)}") |
|
|
| print("\nPushing to Hub...") |
| splits.push_to_hub("AbijahKaj/telephony-amd-dataset", private=True) |
| print("Done! https://huggingface.co/datasets/AbijahKaj/telephony-amd-dataset") |
|
|
| if __name__ == "__main__": |
| asyncio.run(main()) |
|
|