We'll go through the process of creating a set of OpenWhisk actions using the wsk CLI tool that will utilize the libraries you mentioned (numpy, matplotlib, soundfile, librosa, and IPython) to analyze an audio file, generate a spectrogram, and then expose the resulting graph through a URL with a final action. This setup involves creating a Python virtual environment, including the necessary packages, and deploying the actions on OpenWhisk.
Prerequisites
- Apache OpenWhisk CLI (
wsk): Ensure you have the wsk CLI installed and properly configured to communicate with your OpenWhisk instance.
- Python 3.x: The examples below are Python based.
- Docker (optional): Required if you're packing custom dependencies that are not available in the default OpenWhisk Python runtime environment.
Steps
1. Create Python Virtual Environment and Install Dependencies
To ensure portability and to encapsulate the dependencies, we'll create a Python virtual environment and install the required libraries.
# Create a virtual environment
python3 -m venv openwhisk-venv
# Activate the environment
source openwhisk-venv/bin/activate
# Install required libraries
pip install numpy matplotlib soundfile librosa IPython
You'll also need to add a requirements.txt file with all the dependencies if you haven't already:
numpy
matplotlib
soundfile
librosa
IPython
2. Writing the Actions
First, let's write the actions. Given the task, you probably need at least three separate actions: one for loading and preprocessing the audio (load_audio), another for generating the spectrogram (generate_spectrogram), and a third for plotting the spectrogram (plot_spectrogram). Then, a fourth action to serve the plot which involves setting up a web action.
Action 1: load_audio.py
import soundfile as sf
import json
def main(args):
file_path = args.get("file_path", "")
data, samplerate = sf.read(file_path)
response = {
"data": data.tolist(), # Convert numpy array to list for JSON serialization
"samplerate": samplerate
}
return { "body": json.dumps(response) }
Action 2: generate_spectrogram.py
import librosa
import json
import numpy as np
def main(args):
data = np.array(args.get("data"))
samplerate = args.get("samplerate")
S = librosa.feature.melspectrogram(y=data, sr=samplerate, n_mels=128, fmax=8000)
S_DB = librosa.power_to_db(S, ref=np.max)
response = {
"spectrogram": S_DB.tolist() # Convert numpy array to list for JSON serialization
}
return { "body": json.dumps(response) }
Action 3: plot_spectrogram.py
import matplotlib.pyplot as plt
import json
import numpy as np
import base64
from io import BytesIO
def main(args):
S_DB = np.array(args.get("spectrogram"))
plt.figure(figsize=(10, 4))
librosa.display.specshow(S_DB, x_axis='time', y_axis='mel', sr=args.get("samplerate"), fmax=8000)
plt.colorbar(format='%+2.0f dB')
plt.title('Mel-frequency spectrogram')
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf, format='png')
plt.close()
data = base64.b64encode(buf.getbuffer()).decode("ascii")
return {"body": json.dumps({"image": data}) }
3. Packaging Actions with Dependencies
Since the actions depend on libraries that are not in the default OpenWhisk runtime, you will need to package them in a Docker container or use the virtualenv approach to include dependencies. For the sake of brevity, we'll go with a high-level overview of the Docker approach:
Dockerfile
FROM openwhisk/python3action
# Copy local code to the container image.
ENV APP_HOME /pythonAction
WORKDIR $APP_HOME
# Install production dependencies.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
You can build and push this Docker image to a registry where your OpenWhisk platform can access it. Then, when creating the actions with the wsk CLI, you specify this Docker image as the runtime environment.
4. Deploying Actions
You would deploy each action with something along these lines, assuming you have packaged each Python file and its dependencies correctly:
wsk action create load_audio load_audio.py --docker <your_docker_image_with_dependencies>
wsk action create generate_spectrogram generate_spectrogram.py --docker <your_docker_image_with_dependencies>
wsk action create plot_spectrogram plot_spectrogram.py --docker <your_docker_image_with_dependencies>
5. Setting Up Web Action for Exposition
Assuming plot_spectrogram returns an HTML page or a direct link to the image:
wsk action update plot_spectrogram --web true
You can obtain the URL with:
wsk action get plot_spectrogram --url
Note
This guide provides a high-level overview and focuses on setting up and scripting the necessary actions. Specific details like error handling, input validations, and security considerations (especially when exposing APIs publicly) should be adequately addressed in a production scenario.