Spaces:
Running on Zero
Running on Zero
Download latency_test.py from StrangerInAStrangeLand/en-stt-tts: direct link, hf CLI and curl.
- Browser
- Download file 6.59 kB
-
https://huggingface.co/spaces/StrangerInAStrangeLand/en-stt-tts/resolve/main/latency_test.py
- Command line
-
hf download hf://spaces/StrangerInAStrangeLand/en-stt-tts/latency_test.py
-
curl -L -o latency_test.py https://huggingface.co/spaces/StrangerInAStrangeLand/en-stt-tts/resolve/main/latency_test.py
6.59 kB
| #!/usr/bin/env python3 | |
| """Latency test for the deployed Space β run before wiring it in as Hermes' TTS/STT. | |
| Measures what decides the wiring decision: end-to-end wall time per call, and the split | |
| between the app's own GPU-side work (reported in the status line) and everything else | |
| (Gradio queue, ZeroGPU allocation, HTTP, upload/download). That remainder is the ZeroGPU | |
| floor β it is what a voice reply actually pays on top of inference. | |
| Uses the same stdlib client as the production wrappers (~/.hermes/scripts/hf_space_api.py), | |
| so it needs no venv and no third-party packages: | |
| /usr/bin/python3 tests/latency_test.py --runs 3 | |
| Optionally cross-checks one call against gradio_client (if that venv exists) to validate the | |
| hand-rolled HTTP client against the reference implementation. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import statistics | |
| import sys | |
| import time | |
| from pathlib import Path | |
| sys.path.insert(0, "/home/agent/.hermes/scripts") | |
| import hf_space_api as api # noqa: E402 | |
| SHORT_TEXT = ( | |
| "Alright, the transcription job finished cleanly and the report is on your desk. " | |
| "Nothing here needs your attention before tomorrow morning." | |
| ) | |
| LONG_TEXT = ( | |
| "Here is a longer passage, the sort of thing that ends up in a voice reply when the " | |
| "answer needs room to breathe. It keeps going for a few sentences so the segmentation " | |
| "path gets exercised properly, and then it stops. " | |
| ) * 4 | |
| REPORT = Path(__file__).resolve().parent / "latency-report.md" | |
| def stats(label: str, times: list[float]) -> str: | |
| if not times: | |
| return f"{label}: no successful runs" | |
| return ( | |
| f"{label}: min {min(times):.1f}s | median {statistics.median(times):.1f}s | " | |
| f"max {max(times):.1f}s (n={len(times)})" | |
| ) | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--runs", type=int, default=3) | |
| ap.add_argument("--cross-check", action="store_true", | |
| help="also call /speak once via gradio_client for protocol validation") | |
| args = ap.parse_args() | |
| lines: list[str] = [] | |
| def say(text: str = "") -> None: | |
| print(text) | |
| lines.append(text) | |
| host = api.space_base_url() | |
| token = api.resolve_token() | |
| say("# Latency test β HF ZeroGPU speech Space") | |
| say() | |
| say(f"- host: `{host}`") | |
| say(f"- started: {time.strftime('%Y-%m-%d %H:%M:%S')}") | |
| say(f"- token present: {'yes' if token else 'NO (anonymous pool β results will be quota-limited)'}") | |
| say() | |
| # --- TTS --------------------------------------------------------------------------- | |
| say("## Text to speech (`/speak`)") | |
| say() | |
| tts_times: list[float] = [] | |
| statuses: list[str] = [] | |
| for i in range(args.runs): | |
| try: | |
| payload, elapsed = api.timed(api.call, "speak", [SHORT_TEXT, "af_heart", 1.0, 5000]) | |
| except api.SpaceCallError as exc: | |
| say(f"- run {i + 1}: FAILED β {exc}") | |
| continue | |
| status = payload[1] if len(payload) > 1 else "" | |
| statuses.append(status) | |
| tts_times.append(elapsed) | |
| say(f"- run {i + 1}: **{elapsed:.1f}s** wall | {len(SHORT_TEXT)} chars | {status}") | |
| say() | |
| say(stats(f"TTS short ({len(SHORT_TEXT)} chars)", tts_times)) | |
| say() | |
| try: | |
| payload, elapsed = api.timed(api.call, "speak", [LONG_TEXT, "af_heart", 1.0, 5000]) | |
| remote = payload[0].get("path") if isinstance(payload[0], dict) else payload[0] | |
| say(f"- long text ({len(LONG_TEXT)} chars): **{elapsed:.1f}s** wall | " | |
| f"{payload[1] if len(payload) > 1 else ''}") | |
| except api.SpaceCallError as exc: | |
| say(f"- long text: FAILED β {exc}") | |
| remote = None | |
| # --- STT --------------------------------------------------------------------------- | |
| say() | |
| say("## Speech to text (`/transcribe`)") | |
| say() | |
| stt_times: list[float] = [] | |
| texts: list[str] = [] | |
| if remote: | |
| wav = REPORT.parent / "latency-sample.wav" | |
| try: | |
| api.download(str(remote), wav) | |
| say(f"- sample audio: {wav.name}, {wav.stat().st_size} bytes") | |
| remote_path = api.upload_file(wav) | |
| except api.SpaceCallError as exc: | |
| say(f"- sample preparation failed: {exc}") | |
| remote_path = None | |
| if remote_path: | |
| for i in range(args.runs): | |
| try: | |
| payload, elapsed = api.timed( | |
| api.call, "transcribe", [api.file_data(remote_path), 300.0] | |
| ) | |
| except api.SpaceCallError as exc: | |
| say(f"- run {i + 1}: FAILED β {exc}") | |
| continue | |
| text = str(payload[0] or "") | |
| texts.append(text) | |
| stt_times.append(elapsed) | |
| say(f"- run {i + 1}: **{elapsed:.1f}s** wall | {len(text)} chars | " | |
| f"{payload[1] if len(payload) > 1 else ''}") | |
| say() | |
| say(stats("STT (same ~%ss clip)" % round(len(LONG_TEXT) / 15), stt_times)) | |
| if texts: | |
| say() | |
| say(f"- transcript (run 1): {texts[0][:200]!r}") | |
| # --- Optional: cross-check against gradio_client ----------------------------------- | |
| if args.cross_check: | |
| say() | |
| say("## Cross-check: gradio_client vs stdlib client") | |
| try: | |
| from gradio_client import Client | |
| client = Client(api.space_base_url().replace("https://", ""), token=token, | |
| verbose=False) | |
| t0 = time.perf_counter() | |
| wav_path, status = client.predict(SHORT_TEXT, "af_heart", 1.0, 5000, | |
| api_name="/speak") | |
| gc_time = time.perf_counter() - t0 | |
| say(f"- gradio_client: {gc_time:.1f}s | {status} | {wav_path}") | |
| say("- the two clients agreeing on output shape validates the hand-rolled HTTP path") | |
| except Exception as exc: | |
| say(f"- cross-check skipped: {type(exc).__name__}: {exc}") | |
| say() | |
| say("## Reading this") | |
| say() | |
| say("- **wall** is what a Hermes voice reply costs end to end.") | |
| say("- the app's status line reports its own GPU-side timing, so " | |
| "wall minus that = Gradio queue + ZeroGPU allocation + HTTP + transcoding.") | |
| say("- compare against Edge TTS (~1-2s, no GPU) and local faster-whisper on this box.") | |
| REPORT.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| print(f"\nreport: {REPORT}") | |
| return 0 if tts_times else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |