Chapter 1 of ?
python 14 min read

Python for Data Science — Chapter 19: API Setup and Practice

AI APIs — Speech-to-Text & Language Translation

Modern Artificial Intelligence services are delivered over the internet via AI Cloud APIs. In this chapter, we build an end-to-end multi-cloud AI pipeline using Python: transcribing binary audio files into text with Speech to Text API (via POST requests), and translating that transcript into foreign languages with Language Translator API.

🔑
19.1 API Keys & Endpoints
Authentication & Security
🎙️
19.2 Speech-to-Text
Audio POST Binary Request
🌍
19.3 Language Translator
Multilingual AI Model

19.1 API Keys and Endpoints — Cloud Security

To use cloud AI models, services require two critical pieces of information: an Endpoint URL and an API Key.

1. API Endpoint

The web location of the AI service instance on the internet.

https://api.us-south.speech-to-text.watson.cloud.ibm.com
2. API Key (Access Token)

A unique, secret string that authorizes your application and meters your usage.

aX9K_mQ8z7Lp2Wn4vR6tY1uI3oO5pA7s
Key Security Rule: Treat your API key like a password! Cloud providers charge money for API calls. If an unauthorized user gets your key, they can run expensive queries on your account. Never commit API keys into public Git repositories.
Authentication Header: When your Python client makes an HTTP POST or GET request, it includes the API key in the request headers (e.g., Authorization: Bearer <key>). The server validates your identity before processing.
Interactive Key Vault & HTTP Auth Tester

Test how cloud servers respond when valid vs invalid API keys are transmitted in HTTP request headers.

HTTP Header Verification Log200 Authorized
>>> Header: Authorization: Bearer aX9K_mQ8z7Lp2Wn4vR6tY1uI3oO5pA7s >>> Server Response: 200 OK — Authentication Verified!

19.2 Speech-to-Text — Transcribing Audio with Python

To convert spoken audio into written text, your program sends a POST request carrying the raw binary audio bytes to the Speech-to-Text API endpoint. The AI model analyzes the frequency spectrum and returns a structured JSON transcription.

from ibm_watson import SpeechToTextV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

# 1. Authenticate using API Key
authenticator = IAMAuthenticator("YOUR_API_KEY")
s2t = SpeechToTextV1(authenticator=authenticator)

# 2. Set the Service Endpoint URL
s2t.set_service_url("URL_s2t")

# 3. Open audio file in binary read mode ('rb')
filename = "hello_world.wav"
with open(filename, "rb") as audio_file:
    # 4. Send POST request with binary audio payload
    response = s2t.recognize(
        audio=audio_file,
        content_type="audio/wav"
    )

# 5. Extract text from nested JSON response
results = response.get_result()
recognized_text = results["results"][0]["alternatives"][0]["transcript"]
print("Recognized Text:", recognized_text)

Why mode='rb'? Audio files (like .wav or .mp3) contain raw binary bytes, not plain text lines. Using open(filename, 'rb') reads the exact byte stream required by the POST body.

JSON Structure: The API returns results['results'][0]['alternatives'][0]['transcript']. The alternatives list contains hypothesis text sorted by confidence score.
Interactive Speech-to-Text Audio Studio

Select an audio clip, click Transcribe Audio, and watch the POST request transmit the binary audio to the Watson AI model.

Sample 1: Tech Intro
Duration: 4.2s (.wav)
POST /v1/recognize LogReady
>>> Click "Transcribe Audio" to initiate binary POST request.
Try It Yourself »

19.3 Language Translator — AI Text Translation

Once you have transcribed text, you can chain it directly into the Language Translator API to convert it into target languages such as Spanish (es), French (fr), or German (de).

from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

# 1. Authenticate Language Translator
authenticator = IAMAuthenticator("YOUR_API_KEY")
lt = LanguageTranslatorV3(
    version="2018-05-01",
    authenticator=authenticator
)
lt.set_service_url("URL_lt")

# 2. Translate English text to Spanish ('en-es')
translation_response = lt.translate(
    text=recognized_text,
    model_id="en-es"
)

# 3. Extract translated string
result = translation_response.get_result()
spanish_text = result["translations"][0]["translation"]
print("Spanish Translation:", spanish_text)

# 4. Reverse translate back to English ('es-en')
back_to_english = lt.translate(
    text=spanish_text,
    model_id="es-en"
).get_result()["translations"][0]["translation"]
print("Verified English:", back_to_english)

Model IDs: The model_id parameter specifies source language and target language joined by a hyphen (e.g. 'en-es' for English → Spanish, 'en-fr' for English → French).

Language ISO Codes: en = English | es = Spanish | fr = French | de = German | ja = Japanese.
Full End-to-End AI Speech Translation Pipeline

Click Run Full Pipeline to execute the full multi-cloud sequence: Audio .wav → Speech-to-Text → Text Transcript → Language Translator → Multilingual Output.

🎙️
Audio .wav
Binary Source
🤖
Speech-to-Text
POST Request
📝
Transcript
English Text
🌍
Translator AI
en-es Model
Final Result
Translated Text
Pipeline Pipeline Output LogReady
>>> Select a target language and click "Run Full Pipeline".
Try It Yourself »

Chapter 19 Quiz

1. What is the purpose of an API Key in cloud AI services?

2. When sending an audio file to Speech-to-Text API, why do we use open(filename, "rb")?

3. What does the parameter model_id="en-es" mean in Watson Language Translator?

4. Why should API keys be kept secret like passwords?

Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *