Spaces:
Running on Zero
Running on Zero
Upload client_example.py with huggingface_hub
Browse files- client_example.py +129 -0
client_example.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Minimal, dependency-light client for the English STT + TTS Space.
|
| 3 |
+
|
| 4 |
+
Calls the two stable named endpoints:
|
| 5 |
+
|
| 6 |
+
POST/GET /gradio_api/call/transcribe (api_name="/transcribe")
|
| 7 |
+
POST/GET /gradio_api/call/speak (api_name="/speak")
|
| 8 |
+
|
| 9 |
+
gradio_client hides the two-step enqueue->stream protocol, so use it unless you need to
|
| 10 |
+
speak HTTP directly (the raw form is documented at the bottom of this file).
|
| 11 |
+
|
| 12 |
+
Environment (never hardcode credentials):
|
| 13 |
+
EN_SPEECH_SPACE Space id "user/space" or a full https URL. REQUIRED.
|
| 14 |
+
HF_TOKEN Optional Hugging Face token. Sending one matters: an anonymous call
|
| 15 |
+
draws the shared anonymous ZeroGPU allowance (~2 min/day) instead of
|
| 16 |
+
your account quota, and fails with "ZeroGPU quota exceeded" on an
|
| 17 |
+
HTTP 200 response. If unset, gradio_client falls back to the token
|
| 18 |
+
saved by `hf auth login` (~/.cache/huggingface/token).
|
| 19 |
+
|
| 20 |
+
Examples:
|
| 21 |
+
EN_SPEECH_SPACE=user/en-stt-tts HF_TOKEN=hf_xxx \
|
| 22 |
+
python client_example.py audio speech.wav
|
| 23 |
+
EN_SPEECH_SPACE=user/en-stt-tts HF_TOKEN=hf_xxx \
|
| 24 |
+
python client_example.py tts "The quick brown fox." --voice bf_emma --speed 1.1
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import os
|
| 31 |
+
import sys
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_client():
|
| 36 |
+
"""Build an authenticated gradio_client for the Space named in EN_SPEECH_SPACE."""
|
| 37 |
+
from gradio_client import Client
|
| 38 |
+
|
| 39 |
+
space = (os.environ.get("EN_SPEECH_SPACE") or "").strip()
|
| 40 |
+
if not space:
|
| 41 |
+
sys.exit("Set EN_SPEECH_SPACE to the Space id (e.g. user/en-stt-tts) or its URL.")
|
| 42 |
+
# token=None makes gradio_client use the locally saved HF token, if any.
|
| 43 |
+
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 44 |
+
return Client(space, token=token, verbose=False)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def transcribe(client, audio_path: str, max_seconds: float = 300.0):
|
| 48 |
+
"""Upload an audio file, return (transcript, status)."""
|
| 49 |
+
from gradio_client import handle_file
|
| 50 |
+
|
| 51 |
+
transcript, status = client.predict(
|
| 52 |
+
handle_file(audio_path), # -> first positional input (gr.Audio, filepath)
|
| 53 |
+
max_seconds, # -> second positional input (gr.Slider)
|
| 54 |
+
api_name="/transcribe",
|
| 55 |
+
)
|
| 56 |
+
return transcript, status
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def speak(client, text: str, voice: str = "af_heart", speed: float = 1.0,
|
| 60 |
+
max_chars: int = 5000):
|
| 61 |
+
"""Synthesise text, return (local_wav_path, status).
|
| 62 |
+
|
| 63 |
+
gradio_client downloads the generated WAV to a local temp dir and returns its path.
|
| 64 |
+
"""
|
| 65 |
+
wav_path, status = client.predict(
|
| 66 |
+
text, # gr.Textbox
|
| 67 |
+
voice, # gr.Dropdown (value, e.g. "af_heart")
|
| 68 |
+
speed, # gr.Slider (0.5 - 2.0)
|
| 69 |
+
max_chars, # gr.Slider (maximum text length)
|
| 70 |
+
api_name="/speak",
|
| 71 |
+
)
|
| 72 |
+
return wav_path, status
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def main() -> int:
|
| 76 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 77 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 78 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 79 |
+
|
| 80 |
+
p_audio = sub.add_parser("audio", help="transcribe an audio file")
|
| 81 |
+
p_audio.add_argument("file")
|
| 82 |
+
p_audio.add_argument("--max-seconds", type=float, default=300.0)
|
| 83 |
+
|
| 84 |
+
p_tts = sub.add_parser("tts", help="synthesise speech from text")
|
| 85 |
+
p_tts.add_argument("text")
|
| 86 |
+
p_tts.add_argument("--voice", default="af_heart")
|
| 87 |
+
p_tts.add_argument("--speed", type=float, default=1.0)
|
| 88 |
+
p_tts.add_argument("--max-chars", type=int, default=5000)
|
| 89 |
+
p_tts.add_argument("--out", default=None, help="copy the WAV here (optional)")
|
| 90 |
+
|
| 91 |
+
args = ap.parse_args()
|
| 92 |
+
client = get_client()
|
| 93 |
+
|
| 94 |
+
if args.cmd == "audio":
|
| 95 |
+
path = Path(args.file)
|
| 96 |
+
if not path.is_file():
|
| 97 |
+
sys.exit(f"No such file: {path}")
|
| 98 |
+
transcript, status = transcribe(client, str(path), args.max_seconds)
|
| 99 |
+
print(f"status : {status}")
|
| 100 |
+
print(f"transcript : {transcript!r}")
|
| 101 |
+
return 0 if transcript else 1
|
| 102 |
+
|
| 103 |
+
wav_path, status = speak(client, args.text, args.voice, args.speed, args.max_chars)
|
| 104 |
+
print(f"status : {status}")
|
| 105 |
+
print(f"wav : {wav_path}")
|
| 106 |
+
if args.out:
|
| 107 |
+
Path(args.out).write_bytes(Path(wav_path).read_bytes())
|
| 108 |
+
print(f"copied : {args.out}")
|
| 109 |
+
return 0
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
raise SystemExit(main())
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------------------------------
|
| 116 |
+
# Raw HTTP, no gradio_client (for reference — the enqueue + SSE dance):
|
| 117 |
+
#
|
| 118 |
+
# import json, os, requests
|
| 119 |
+
# base = "https://<user>-<space>.hf.space"
|
| 120 |
+
# hdr = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}
|
| 121 |
+
# r = requests.post(f"{base}/gradio_api/call/transcribe",
|
| 122 |
+
# json={"data": ["<local path or FileData>", 300]}, headers=hdr)
|
| 123 |
+
# event_id = r.json()["event_id"]
|
| 124 |
+
# for line in requests.get(f"{base}/gradio_api/call/transcribe/{event_id}",
|
| 125 |
+
# headers=hdr, stream=True).iter_lines():
|
| 126 |
+
# ... # lines look like: b'data: ["transcript", "status"]'
|
| 127 |
+
#
|
| 128 |
+
# A refusal (quota, queue, auth) arrives as an *error envelope inside the SSE payload*
|
| 129 |
+
# with HTTP 200 — check for an "error" key before trusting the result.
|