SDKs and tools
Python SDK
shihab-asr for Python 3.9+: sync, async and streaming.
Install
Terminal
pip install shihab-asr
# until the package is live on PyPI:
pip install https://voice.shihab.co.uk/sdk/shihab_asr-1.1.0-py3-none-any.whl
# microphone streaming in the CLI:
pip install "shihab-asr[mic]"Python 3.9 or newer.
Create a client
python
from shihab_asr import ShihabASR
client = ShihabASR() # reads SHIHAB_API_KEY
client = ShihabASR(
api_key="shk_live_...",
timeout=600, # seconds per request
max_retries=2, # 429, 503 and connection errors
)Transcribe a file
python
result = client.listen("voice-note.ogg", numerals=True, tags=["support"])
print(result.transcript)
for seg in result.segments:
print(f"{seg.start:6.2f} {seg.end:6.2f} {seg.text}")
print(result.duration, result.usage.billed_seconds, result.usage.cost_usd, result.request_id)
# bytes, a binary file object, or a URL the API downloads
with open("call.wav", "rb") as f:
client.listen(f)
client.listen(url="https://example.com/recordings/call-1029.mp3")| Option | Default | Meaning |
|---|---|---|
| numerals | False | Digits instead of number words. |
| timestamps | "segment" | "none" skips segments. |
| tags | [] | Up to 5 labels for your logs. |
| language | "ar" | ar, ar-PS, ar-EG, ... (ar-XX) |
| model | "shihab-asr-v1" | Shihab Voice, the only model. |
Async jobs
python
job = client.transcriptions.create(
"meeting.m4a", # or url="https://..."
webhook_url="https://example.com/hooks/shihab",
metadata={"meeting_id": "42"},
)
job = client.transcriptions.wait(job.id, timeout=3600)
if job.status == "completed":
print(job.transcript)
else:
print(job.error.code, job.error.message)
page = client.transcriptions.list(limit=20, status="completed") # page.data, page.has_more, page.next_cursor
client.transcriptions.delete(job.id) # deletes the stored transcriptStreaming
python
import threading
with client.stream(encoding="linear16", sample_rate=16000, interim_results=True) as stream:
def feed():
with open("call.pcm", "rb") as f: # 16 kHz, 16-bit mono PCM
while chunk := f.read(3200): # 100 ms
stream.send(chunk)
stream.close() # sends CloseStream, waits for the last results
threading.Thread(target=feed, daemon=True).start()
for event in stream:
if event.type == "Results" and event.is_final:
print(event.transcript)
elif event.type == "UtteranceEnd":
print("(pause)")
print(stream.finished.audio_seconds, stream.finished.cost_usd)send() works from any thread; finalize() flushes the current utterance; a KeepAlive is sent for you while no audio flows. Telephony: encoding="mulaw", sample_rate=8000.
Text to speech
speak() returns the whole audio; speak_stream() hands it over chunk by chunk while it is generated. See Text to speech.
from shihab_asr import ShihabASR
client = ShihabASR() # reads SHIHAB_API_KEY
speech = client.speak("أهلا وسهلا، معك شهاب. كيف بقدر أساعدك اليوم؟", voice="ps-female", dialect="ps")
speech.save("hello.mp3")
print(speech.characters, speech.cost_usd) # 44 "0.00132"asyncio
python
import asyncio
from shihab_asr import AsyncShihabASR
async def main():
async with AsyncShihabASR() as client:
result = await client.listen("voice-note.ogg")
print(result.transcript)
async with client.stream(sample_rate=16000) as stream:
asyncio.create_task(feed(stream)) # await stream.send(chunk) ... await stream.close()
async for event in stream:
if event.type == "Results" and event.is_final:
print(event.transcript)
asyncio.run(main())Webhook verification
Python
# pip install fastapi uvicorn shihab-asr
import os
from fastapi import FastAPI, Header, HTTPException, Request, Response
from shihab_asr import WebhookVerificationError, webhooks
app = FastAPI()
SECRET = os.environ["SHIHAB_WEBHOOK_SECRET"]
@app.post("/hooks/shihab", status_code=204)
async def shihab_webhook(request: Request, shihab_signature: str = Header(None)) -> Response:
raw = await request.body() # the raw bytes: never re-serialize before verifying
try:
event = webhooks.verify(raw, shihab_signature, SECRET)
except WebhookVerificationError:
raise HTTPException(status_code=400) from None
if event.type == "transcription.completed":
print(event.data.id, event.data.transcript)
else:
print(event.data.id, "failed:", event.data.error)
return Response(status_code=204)Errors and retries
Every API error raises a subclass of shihab_asr.APIError with status_code, type, code, message, param and request_id. See Errors.
Python
from shihab_asr import (
APIError,
BadRequestError,
InsufficientCreditsError,
RateLimitError,
ShihabASR,
)
client = ShihabASR() # retries 429, 503 and connection errors automatically
try:
result = client.listen("call.m4a")
except InsufficientCreditsError:
print("Out of credit: top up in the console")
except BadRequestError as e:
print("Check the audio or parameters:", e.code, e.param)
except RateLimitError as e:
print("Still rate limited after retries; wait", e.retry_after, "s")
except APIError as e:
print(e.status_code, e.code, e.message, e.request_id) # quote request_id to supportNeed help? Email [email protected] or message us on WhatsApp.