forked from speaches-ai/speaches
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeach_cli.py
More file actions
823 lines (705 loc) Β· 28.9 KB
/
speach_cli.py
File metadata and controls
823 lines (705 loc) Β· 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
#!/usr/bin/env python3
"""
Speaches Audio API - Complete CLI Tool
=====================================
A self-contained script for audio model benchmarking and testing.
Required dependencies (install with):
pip install requests click tabulate torch torchaudio
export SPEACHES_API_URL=caas-replica-endpoint
Usage Examples:
# Health check
python speaches_cli.py health-check
# List all models
python speaches_cli.py list-models
# List available voices
python speaches_cli.py list-voices
python speaches_cli.py list-voices --language en --gender female
# Download and load model
python speaches_cli.py download-model Systran/faster-whisper-tiny
python speaches_cli.py load-model Systran/faster-whisper-tiny
# Generate speech
python speaches_cli.py create-speech "Hello world" --output hello.wav
# Transcribe audio
python speaches_cli.py transcribe audio.wav --model Systran/faster-whisper-tiny
# Run benchmarks with table output
python speaches_cli.py benchmark --models Systran/faster-whisper-tiny,openai/whisper-base
Environment Variable:
export SPEACHES_API_URL=https://your-api-url
"""
import os
import sys
import time
import json
import logging
from pathlib import Path
from typing import Dict, Any, Optional
import tempfile
try:
import requests
import click
from tabulate import tabulate
import torch
import torchaudio
except ImportError as e:
print(f"β Missing dependency: {e}")
print("π¦ Install with: pip install requests click tabulate torch torchaudio")
sys.exit(1)
# Configure logging
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
class SpeachesAPI:
"""Complete Speaches API client"""
def __init__(self, base_url: str):
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update({"Content-Type": "application/json"})
def health_check(self) -> Dict[str, Any]:
"""Check API health status"""
try:
response = self.session.get(f"{self.base_url}/health", timeout=10)
if response.status_code == 200:
# Health endpoint returns plain text "OK", not JSON
if response.text.strip() == "OK":
return {"status": "healthy", "details": {"message": "OK"}}
else:
try:
return {"status": "healthy", "details": response.json()}
except (requests.exceptions.JSONDecodeError, json.JSONDecodeError):
return {
"status": "healthy",
"details": {"message": response.text},
}
else:
return {
"status": "unhealthy",
"code": response.status_code,
"details": response.text,
}
except Exception as e:
return {"status": "error", "error": str(e)}
def list_models(self, task: Optional[str] = None) -> Dict[str, Any]:
"""List available models"""
try:
# Get STT models
stt_response = self.session.get(
f"{self.base_url}/v1/registry?task=automatic-speech-recognition",
timeout=30,
)
stt_data = (
stt_response.json() if stt_response.status_code == 200 else {"data": []}
)
stt_models = stt_data.get("data", [])
# Get TTS models
tts_response = self.session.get(
f"{self.base_url}/v1/registry?task=text-to-speech", timeout=30
)
tts_data = (
tts_response.json() if tts_response.status_code == 200 else {"data": []}
)
tts_models = tts_data.get("data", [])
return {
"stt_models": stt_models,
"tts_models": tts_models,
"total_stt": len(stt_models),
"total_tts": len(tts_models),
}
except Exception as e:
return {"error": str(e)}
def download_model(self, model_id: str) -> Dict[str, Any]:
"""Download a remote model"""
try:
headers = {}
# Get API key from environment variable
api_key = os.getenv("SPEACHES_API_KEY")
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
response = self.session.post(
f"{self.base_url}/v1/models/{model_id}",
timeout=300, # 5 minutes for download
headers=headers,
)
if response.status_code in [200, 201]:
# API returns plain text response, not JSON
response_text = response.text.strip()
if "already exists" in response_text.lower():
return {"status": "already_exists", "details": response_text}
else:
return {"status": "success", "details": {"message": response_text}}
else:
return {
"status": "error",
"code": response.status_code,
"details": response.text,
}
except Exception as e:
return {"status": "error", "error": str(e)}
def load_model(self, model_id: str) -> Dict[str, Any]:
"""Load model into memory"""
try:
response = self.session.post(
f"{self.base_url}/api/ps/{model_id}", timeout=120
)
if response.status_code in [200, 201]:
# API returns plain text response, not JSON
response_text = response.text.strip()
return {"status": "success", "details": {"message": response_text}}
elif response.status_code == 409:
# Model already loaded
return {"status": "already_loaded", "details": response.text.strip()}
else:
return {
"status": "error",
"code": response.status_code,
"details": response.text,
}
except Exception as e:
return {"status": "error", "error": str(e)}
def get_loaded_models(self) -> Dict[str, Any]:
"""Get currently loaded models"""
try:
response = self.session.get(f"{self.base_url}/api/ps", timeout=10)
if response.status_code == 200:
return response.json()
else:
return {"models": []}
except Exception as e:
return {"error": str(e)}
def transcribe_audio(self, audio_file: Path, model_id: str) -> Dict[str, Any]:
"""Transcribe audio file"""
try:
with open(audio_file, "rb") as f:
files = {"file": (audio_file.name, f, "audio/wav")}
data = {"model": model_id}
response = self.session.post(
f"{self.base_url}/v1/audio/transcriptions",
files=files,
data=data,
timeout=300,
)
if response.status_code == 200:
return {"status": "success", "transcription": response.json()}
else:
return {
"status": "error",
"code": response.status_code,
"details": response.text,
}
except Exception as e:
return {"status": "error", "error": str(e)}
def create_speech(
self, text: str, model_id: str = None, voice: str = "alloy"
) -> Dict[str, Any]:
"""Generate speech from text"""
try:
payload = {"input": text, "voice": voice}
if model_id:
payload["model"] = model_id
response = self.session.post(
f"{self.base_url}/v1/audio/speech", json=payload, timeout=120
)
if response.status_code == 200:
return {"status": "success", "audio_data": response.content}
else:
return {
"status": "error",
"code": response.status_code,
"details": response.text,
}
except Exception as e:
return {"status": "error", "error": str(e)}
def get_available_voices(self) -> Dict[str, Any]:
"""Get all available voices from TTS models"""
try:
# Get TTS models which contain voice information
tts_response = self.session.get(
f"{self.base_url}/v1/registry?task=text-to-speech", timeout=30
)
if tts_response.status_code != 200:
return {"error": "Failed to fetch TTS models"}
tts_data = tts_response.json()
tts_models = tts_data.get("data", [])
# Extract all voices from TTS models
voices = []
for model in tts_models:
model_voices = model.get("voices", [])
for voice in model_voices:
voices.append(
{
"model": model.get("id", "Unknown"),
"voice_id": voice.get("id", "Unknown"),
"name": voice.get("name", "Unknown"),
"language": voice.get("language", "Unknown"),
"gender": voice.get("gender", "Unknown"),
}
)
return {
"voices": voices,
"total_voices": len(voices),
"total_models": len(tts_models),
}
except Exception as e:
return {"error": str(e)}
def get_base_url(base_url: Optional[str] = None) -> str:
"""Get API base URL from CLI argument or environment"""
if base_url:
click.echo(f"π Using CLI-provided URL: {base_url}")
return base_url
elif os.getenv("SPEACHES_API_URL"):
url = os.getenv("SPEACHES_API_URL")
click.echo(f"π Using environment URL: {url}")
return url
else:
click.echo("β Error: No API URL provided!")
click.echo(
"π‘ Set SPEACHES_API_URL environment variable or use --base-url flag"
)
click.echo(" Example: export SPEACHES_API_URL=https://your-api-url")
sys.exit(1)
def create_dummy_audio(text: str, output_file: Path, duration: float = 3.0):
"""Create a simple audio file for testing"""
sample_rate = 16000
t = torch.linspace(0, duration, int(sample_rate * duration))
# Create a simple sine wave
freq = 440 # A4 note
audio = 0.3 * torch.sin(2 * 3.14159 * freq * t)
audio = audio.unsqueeze(0) # Add channel dimension
torchaudio.save(output_file, audio, sample_rate)
@click.group()
@click.option(
"--base-url", help="Speaches API base URL (overrides SPEACHES_API_URL env var)"
)
@click.pass_context
def cli(ctx, base_url):
"""Speaches Audio API CLI Tool
Environment Variables:
SPEACHES_API_URL: Default API base URL
"""
ctx.ensure_object(dict)
ctx.obj["base_url"] = get_base_url(base_url)
ctx.obj["api"] = SpeachesAPI(ctx.obj["base_url"])
@cli.command("health-check")
@click.pass_context
def health_check(ctx):
"""Check API health status"""
click.echo("π Checking API health...")
result = ctx.obj["api"].health_check()
if result["status"] == "healthy":
click.echo("β
API is healthy")
if "details" in result:
click.echo(f"π Details: {json.dumps(result['details'], indent=2)}")
elif result["status"] == "unhealthy":
click.echo(f"β οΈ API returned status {result['code']}")
click.echo(f"Details: {result['details']}")
else:
click.echo(f"β API health check failed: {result['error']}")
@cli.command("list-models")
@click.option(
"--task",
type=click.Choice(["stt", "tts", "all"]),
default="all",
help="Filter by task type",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["table", "json"]),
default="table",
help="Output format",
)
@click.pass_context
def list_models(ctx, task, output_format):
"""List available models"""
click.echo("π Discovering available models...")
result = ctx.obj["api"].list_models()
if "error" in result:
click.echo(f"β Error listing models: {result['error']}")
return
if output_format == "json":
click.echo(json.dumps(result, indent=2))
return
# Table format
click.echo("\nπ Model Summary:")
click.echo(f" π€ STT Models: {result['total_stt']}")
click.echo(f" π TTS Models: {result['total_tts']}")
if task in ["stt", "all"] and result["stt_models"]:
click.echo(f"\nπ€ STT Models ({len(result['stt_models'])}):")
stt_table = []
for i, model in enumerate(result["stt_models"], 1): # Show first 20
model_info = model if isinstance(model, dict) else {"id": model}
stt_table.append(
[
i,
model_info.get("id", model),
model_info.get("owner", "Unknown"),
", ".join(model_info.get("language", ["Unknown"])[:3]),
]
)
headers = ["#", "Model ID", "Owner", "Languages"]
click.echo(tabulate(stt_table, headers=headers, tablefmt="grid"))
if len(result["stt_models"]) > 20:
click.echo(f"... and {len(result['stt_models']) - 20} more STT models")
if task in ["tts", "all"] and result["tts_models"]:
click.echo(f"\nπ TTS Models ({len(result['tts_models'])}):")
tts_table = []
for i, model in enumerate(result["tts_models"], 1): # Show all
model_info = model if isinstance(model, dict) else {"id": model}
tts_table.append(
[
i,
model_info.get("id", model),
model_info.get("owner", "Unknown"),
", ".join(model_info.get("language", ["Unknown"])[:3]),
]
)
headers = ["#", "Model ID", "Owner", "Languages"]
click.echo(tabulate(tts_table, headers=headers, tablefmt="grid"))
if len(result["tts_models"]) > 20:
click.echo(f"... and {len(result['tts_models']) - 20} more TTS models")
@cli.command("list-voices")
@click.option("--language", help="Filter by language (e.g., en, en-us, de, etc.)")
@click.option(
"--gender",
type=click.Choice(["male", "female", "all"]),
default="all",
help="Filter by gender",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["table", "json"]),
default="table",
help="Output format",
)
@click.pass_context
def list_voices(ctx, language, gender, output_format):
"""List available voices for TTS models"""
click.echo("π Discovering available voices...")
result = ctx.obj["api"].get_available_voices()
if "error" in result:
click.echo(f"β Error listing voices: {result['error']}")
return
if output_format == "json":
click.echo(json.dumps(result, indent=2))
return
voices = result["voices"]
# Apply filters
if language:
voices = [v for v in voices if language.lower() in v["language"].lower()]
if gender != "all":
voices = [v for v in voices if v["gender"].lower() == gender.lower()]
# Table format
click.echo("\nπ Voice Summary:")
click.echo(f" π Total Voices: {len(voices)}")
click.echo(f" π€ Total TTS Models: {result['total_models']}")
if voices:
click.echo(f"\nπ£οΈ Available Voices ({len(voices)}):")
# Group by language for better organization
voices_by_lang = {}
for voice in voices:
lang = voice["language"]
if lang not in voices_by_lang:
voices_by_lang[lang] = []
voices_by_lang[lang].append(voice)
for lang, lang_voices in sorted(voices_by_lang.items()):
if (
len(voices_by_lang) > 1
): # Only show language headers if multiple languages
click.echo(f"\nπ Language: {lang.upper()} ({len(lang_voices)} voices)")
voice_table = []
for i, voice in enumerate(lang_voices, 1):
# Truncate long model names for display
model_name = voice["model"].split("/")[-1][:30]
if len(voice["model"].split("/")[-1]) > 30:
model_name += "..."
voice_table.append(
[
i,
voice["name"],
voice["voice_id"],
voice["gender"].title(),
model_name,
]
)
headers = ["#", "Voice Name", "Voice ID", "Gender", "Model"]
click.echo(tabulate(voice_table, headers=headers, tablefmt="grid"))
else:
click.echo("No voices found matching the specified criteria.")
@cli.command("download-model")
@click.argument("model_id")
@click.pass_context
def download_model(ctx, model_id):
"""Download a remote model"""
click.echo(f"π₯ Downloading model: {model_id}")
start_time = time.time()
result = ctx.obj["api"].download_model(model_id)
download_time = time.time() - start_time
if result["status"] == "success":
click.echo(f"β
Model downloaded successfully in {download_time:.1f}s")
if "details" in result:
click.echo(f"π Details: {json.dumps(result['details'], indent=2)}")
elif result["status"] == "already_exists":
click.echo(f"βΉοΈ Model already exists: {result.get('details')}")
else:
click.echo(f"β Download failed: {result.get('details', result.get('error'))}")
@cli.command("load-model")
@click.argument("model_id")
@click.pass_context
def load_model(ctx, model_id):
"""Load model into memory"""
click.echo(f"π§ Loading model into memory: {model_id}")
# Check if already loaded
loaded_models = ctx.obj["api"].get_loaded_models()
if "models" in loaded_models and model_id in loaded_models["models"]:
click.echo(f"βΉοΈ Model {model_id} is already loaded in memory")
return
start_time = time.time()
result = ctx.obj["api"].load_model(model_id)
load_time = time.time() - start_time
if result["status"] == "success":
click.echo(f"β
Model loaded successfully in {load_time:.1f}s")
if "details" in result:
click.echo(f"π Details: {json.dumps(result['details'], indent=2)}")
elif result["status"] == "already_loaded":
click.echo(f"βΉοΈ Model already loaded: {result.get('details')}")
else:
click.echo(f"β Load failed: {result.get('details', result.get('error'))}")
@cli.command("create-speech")
@click.argument("text")
@click.option("--model", help="TTS model to use")
@click.option("--voice", default="alloy", help="Voice to use (default: alloy)")
@click.option("--output", "-o", required=True, help="Output audio file path")
@click.pass_context
def create_speech(ctx, text, model, voice, output):
"""Generate speech from text"""
click.echo(f"π Generating speech: '{text[:50]}{'...' if len(text) > 50 else ''}'")
start_time = time.time()
result = ctx.obj["api"].create_speech(text, model, voice)
generation_time = time.time() - start_time
if result["status"] == "success":
# Save audio data to file
with open(output, "wb") as f:
f.write(result["audio_data"])
file_size = len(result["audio_data"]) / 1024 # KB
click.echo(f"β
Speech generated successfully in {generation_time:.1f}s")
click.echo(f"π Saved to: {output} ({file_size:.1f} KB)")
else:
click.echo(
f"β Speech generation failed: {result.get('details', result.get('error'))}"
)
@cli.command("transcribe")
@click.argument("audio_file", type=click.Path(exists=True, path_type=Path))
@click.option("--model", required=True, help="STT model to use")
@click.pass_context
def transcribe(ctx, audio_file, model):
"""Transcribe audio file to text"""
click.echo(f"π€ Transcribing: {audio_file.name} with {model}")
# Check if model is loaded, load if necessary
loaded_models = ctx.obj["api"].get_loaded_models()
if "models" not in loaded_models or model not in loaded_models["models"]:
click.echo(f"π§ Model not loaded, loading {model}...")
load_result = ctx.obj["api"].load_model(model)
if load_result["status"] != "success":
click.echo(
f"β Failed to load model: {load_result.get('details', load_result.get('error'))}"
)
return
click.echo("β
Model loaded successfully")
start_time = time.time()
result = ctx.obj["api"].transcribe_audio(audio_file, model)
transcription_time = time.time() - start_time
if result["status"] == "success":
transcription = result["transcription"]
text = transcription.get("text", "No transcription text returned")
click.echo(f"β
Transcription completed in {transcription_time:.1f}s")
click.echo(f"π Text: {text}")
# Show additional details if available
if isinstance(transcription, dict):
if "language" in transcription:
click.echo(f"π Language: {transcription['language']}")
if "duration" in transcription:
click.echo(f"β±οΈ Duration: {transcription['duration']:.1f}s")
else:
click.echo(
f"β Transcription failed: {result.get('details', result.get('error'))}"
)
@cli.command("benchmark")
@click.option(
"--models", required=True, help="Comma-separated list of models to benchmark"
)
@click.option(
"--audio-file",
type=click.Path(exists=True, path_type=Path),
help="Audio file for STT testing",
)
@click.option("--text", help="Text for TTS testing")
@click.option(
"--task",
type=click.Choice(["stt", "tts", "both"]),
default="stt",
help="Task to benchmark",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["table", "json"]),
default="table",
help="Output format",
)
@click.pass_context
def benchmark(ctx, models, audio_file, text, task, output_format):
"""Run performance benchmarks on multiple models"""
model_list = [m.strip() for m in models.split(",")]
click.echo(f"π§ͺ Benchmarking {len(model_list)} models...")
# Create test files if not provided
if task in ["stt", "both"] and not audio_file:
click.echo("π Creating test audio file...")
temp_dir = Path(tempfile.gettempdir())
audio_file = temp_dir / "test_audio.wav"
create_dummy_audio(
"This is a test recording for speech recognition.", audio_file
)
click.echo(f"π Using temporary audio: {audio_file}")
if task in ["tts", "both"] and not text:
text = "This is a test sentence for speech synthesis evaluation."
click.echo(f"π Using test text: {text}")
results = []
api = ctx.obj["api"]
for i, model in enumerate(model_list, 1):
click.echo(f"\nπ Testing model {i}/{len(model_list)}: {model}")
model_result = {
"model": model,
"stt_result": None,
"tts_result": None,
"errors": [],
}
try:
# Ensure model is loaded
load_result = api.load_model(model)
if load_result["status"] != "success":
model_result["errors"].append(
f"Failed to load model: {load_result.get('details', load_result.get('error'))}"
)
results.append(model_result)
continue
# STT Benchmark
if task in ["stt", "both"]:
stt_start = time.time()
stt_result = api.transcribe_audio(audio_file, model)
stt_time = time.time() - stt_start
if stt_result["status"] == "success":
transcription = stt_result["transcription"]
model_result["stt_result"] = {
"time": stt_time,
"text": transcription.get("text", ""),
"language": transcription.get("language", "unknown"),
"success": True,
}
click.echo(
f" π€ STT: {stt_time:.2f}s - '{transcription.get('text', '')[:50]}'"
)
else:
model_result["stt_result"] = {"time": stt_time, "success": False}
model_result["errors"].append(
f"STT failed: {stt_result.get('details', stt_result.get('error'))}"
)
# TTS Benchmark
if task in ["tts", "both"]:
tts_start = time.time()
tts_result = api.create_speech(text, model)
tts_time = time.time() - tts_start
if tts_result["status"] == "success":
audio_size = len(tts_result["audio_data"])
model_result["tts_result"] = {
"time": tts_time,
"audio_size": audio_size,
"success": True,
}
click.echo(
f" π TTS: {tts_time:.2f}s - {audio_size / 1024:.1f}KB audio"
)
else:
model_result["tts_result"] = {"time": tts_time, "success": False}
model_result["errors"].append(
f"TTS failed: {tts_result.get('details', tts_result.get('error'))}"
)
except Exception as e:
model_result["errors"].append(f"Benchmark error: {str(e)}")
click.echo(f" β Error: {e}")
results.append(model_result)
# Display results
if output_format == "json":
click.echo(json.dumps(results, indent=2))
return
# Table format
click.echo("\n" + "=" * 80)
click.echo("π BENCHMARK RESULTS")
click.echo("=" * 80)
if task in ["stt", "both"]:
click.echo("\nπ€ STT PERFORMANCE")
stt_table = []
for r in results:
if r["stt_result"]:
stt = r["stt_result"]
stt_table.append(
[
r["model"].split("/")[-1][:20],
f"{stt['time']:.2f}s" if stt["success"] else "FAILED",
"β
" if stt["success"] else "β",
stt.get("language", "N/A"),
(
stt.get("text", "")[:30] + "..."
if len(stt.get("text", "")) > 30
else stt.get("text", "")
)
if stt["success"]
else "ERROR",
]
)
if stt_table:
headers = ["Model", "Time", "Status", "Language", "Transcription"]
click.echo(tabulate(stt_table, headers=headers, tablefmt="grid"))
if task in ["tts", "both"]:
click.echo("\nπ TTS PERFORMANCE")
tts_table = []
for r in results:
if r["tts_result"]:
tts = r["tts_result"]
tts_table.append(
[
r["model"].split("/")[-1][:20],
f"{tts['time']:.2f}s" if tts["success"] else "FAILED",
"β
" if tts["success"] else "β",
f"{tts.get('audio_size', 0) / 1024:.1f}KB"
if tts["success"]
else "N/A",
]
)
if tts_table:
headers = ["Model", "Time", "Status", "Audio Size"]
click.echo(tabulate(tts_table, headers=headers, tablefmt="grid"))
# Summary
successful_models = [r for r in results if not r["errors"]]
click.echo("\nπ SUMMARY")
click.echo(f" Total models tested: {len(results)}")
click.echo(f" Successful: {len(successful_models)}")
click.echo(f" Failed: {len(results) - len(successful_models)}")
if task == "stt" or task == "both":
stt_times = [
r["stt_result"]["time"]
for r in results
if r["stt_result"] and r["stt_result"]["success"]
]
if stt_times:
click.echo(f" STT avg time: {sum(stt_times) / len(stt_times):.2f}s")
click.echo(f" STT fastest: {min(stt_times):.2f}s")
if task == "tts" or task == "both":
tts_times = [
r["tts_result"]["time"]
for r in results
if r["tts_result"] and r["tts_result"]["success"]
]
if tts_times:
click.echo(f" TTS avg time: {sum(tts_times) / len(tts_times):.2f}s")
click.echo(f" TTS fastest: {min(tts_times):.2f}s")
click.echo("=" * 80)
if __name__ == "__main__":
cli()