Skip to content

Commit cef8e82

Browse files
techpro-aimlapigitbook-bot
authored andcommitted
GITBOOK-724: docs: add example for stable-audio
1 parent 11e3781 commit cef8e82

4 files changed

Lines changed: 360 additions & 91 deletions

File tree

docs/SUMMARY.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,6 @@
379379
* [3D-Generating Models](api-references/3d-generating-models/README.md)
380380
* [Stability AI](api-references/3d-generating-models/Stability-AI/README.md)
381381
* [triposr](api-references/3d-generating-models/Stability-AI/triposr.md)
382-
* [Copy of triposr](api-references/3d-generating-models/stability-ai/triposr-1.md)
383382
* [Vision Models](api-references/vision-models/README.md)
384383
* [Image Analysis](api-references/vision-models/image-analysis.md)
385384
* [OCR: Optical Character Recognition](api-references/vision-models/ocr-optical-character-recognition/README.md)

docs/api-references/3d-generating-models/stability-ai/triposr-1.md

Lines changed: 0 additions & 80 deletions
This file was deleted.

docs/api-references/music-models/Stability-AI/stable-audio.md

Lines changed: 233 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ If you don’t have an API key for the AI/ML API yet, feel free to use our [Quic
2222

2323
## API Schemas
2424

25-
{% openapi src="../../../.gitbook/assets/stable-audio.json" path="/v2/generate/audio" method="post" %}
26-
[stable-audio.json](../../../.gitbook/assets/stable-audio.json)
27-
{% endopenapi %}
25+
{% openapi-operation spec="stable-audio" path="/v2/generate/audio" method="post" %}
26+
[OpenAPI stable-audio](https://raw.githubusercontent.com/aimlapi/api-docs/refs/heads/main/docs/api-references/music-models/Stability-AI/stable-audio.json)
27+
{% endopenapi-operation %}
2828

2929
### Retrieve the generated music sample from the server <a href="#retrieve-the-generated-video-from-the-server" id="retrieve-the-generated-video-from-the-server"></a>
3030

@@ -33,3 +33,233 @@ After sending a request for music generation, this task is added to the queue. B
3333
{% openapi src="../../../.gitbook/assets/Lyria-2-pair.json" path="/v2/generate/audio" method="get" %}
3434
[Lyria-2-pair.json](../../../.gitbook/assets/Lyria-2-pair.json)
3535
{% endopenapi %}
36+
37+
## Full Example: Generating and Retrieving the Audio From the Server <a href="#full-example-generating-and-retrieving-the-video-from-the-server" id="full-example-generating-and-retrieving-the-video-from-the-server"></a>
38+
39+
The code below creates a audio generation task, then automatically polls the server every **10** seconds until it finally receives the video URL.
40+
41+
{% tabs %}
42+
{% tab title="Python" %}
43+
{% code overflow="wrap" %}
44+
```python
45+
import time
46+
import requests
47+
48+
# Insert your AI/ML API key instead of <YOUR_AIMLAPI_KEY>:
49+
aimlapi_key = '<YOUR_AIMLAPI_KEY>'
50+
51+
# Creating and sending an audio generation task to the server (returns a generation ID)
52+
def generate_audio():
53+
url = "https://api.aimlapi.com/v2/generate/audio"
54+
payload = {
55+
"model": "elevenlabs/eleven_music",
56+
"prompt": "lo-fi pop hip-hop ambient music, slow intro: 10 s, then faster and with loud bass: 10 s",
57+
"seconds_total": 20,
58+
}
59+
headers = {"Authorization": f"Bearer {aimlapi_key}", "Content-Type": "application/json"}
60+
61+
response = requests.post(url, json=payload, headers=headers)
62+
63+
if response.status_code >= 400:
64+
print(f"Error: {response.status_code} - {response.text}")
65+
else:
66+
response_data = response.json()
67+
print("Generation: ", response_data)
68+
return response_data
69+
70+
71+
# Requesting the result of the generation task from the server using the generation_id:
72+
def retrieve_audio(gen_id):
73+
url = "https://api.aimlapi.com/v2/generate/audio"
74+
params = {
75+
"generation_id": gen_id,
76+
}
77+
headers = {"Authorization": f"Bearer {aimlapi_key}", "Content-Type": "application/json"}
78+
response = requests.get(url, params=params, headers=headers)
79+
return response.json()
80+
81+
# This is the main function of the program. From here, we sequentially call the audio generation and then repeatedly request the result from the server every 10 seconds:
82+
def main():
83+
generation_response = generate_audio()
84+
gen_id = generation_response.get("id")
85+
86+
if gen_id:
87+
start_time = time.time()
88+
89+
timeout = 600
90+
while time.time() - start_time < timeout:
91+
response_data = retrieve_audio(gen_id)
92+
93+
if response_data is None:
94+
print("Error: No response from API")
95+
break
96+
97+
status = response_data.get("status")
98+
99+
if status in ["waiting", "queued", "generating"]:
100+
print(f"Status: {status}. Checking again in 10 seconds.")
101+
time.sleep(10)
102+
else:
103+
print("Generation complete:/n", response_data)
104+
return response_data
105+
106+
print("Timeout reached. Stopping.")
107+
return None
108+
109+
110+
if __name__ == "__main__":
111+
main()
112+
```
113+
{% endcode %}
114+
{% endtab %}
115+
116+
{% tab title="JavaScript" %}
117+
{% code overflow="wrap" %}
118+
```javascript
119+
const https = require("https");
120+
const { URL } = require("url");
121+
122+
// Replace <YOUR_AIMLAPI_KEY> with your actual AI/ML API key
123+
const apiKey = "<YOUR_AIMLAPI_KEY>";
124+
const baseUrl = "https://api.aimlapi.com/v2";
125+
126+
// Creating and sending a audio generation task to the server
127+
function generateAudio(callback) {
128+
const data = JSON.stringify({
129+
model: "elevenlabs/eleven_music",
130+
prompt: "lo-fi pop hip-hop ambient music, slow intro: 10 s, then faster and with loud bass: 10 s",
131+
seconds_total: 20,
132+
});
133+
134+
const url = new URL(`${baseUrl}/generate/audio`);
135+
const options = {
136+
method: "POST",
137+
headers: {
138+
"Authorization": `Bearer ${apiKey}`,
139+
"Content-Type": "application/json",
140+
"Content-Length": Buffer.byteLength(data),
141+
},
142+
};
143+
144+
const req = https.request(url, options, (res) => {
145+
let body = "";
146+
res.on("data", (chunk) => body += chunk);
147+
res.on("end", () => {
148+
if (res.statusCode >= 400) {
149+
console.error(`Error: ${res.statusCode} - ${body}`);
150+
callback(null);
151+
} else {
152+
const parsed = JSON.parse(body);
153+
callback(parsed);
154+
}
155+
});
156+
});
157+
158+
req.on("error", (err) => console.error("Request error:", err));
159+
req.write(data);
160+
req.end();
161+
}
162+
163+
// Requesting the result of the task from the server using the generation_id
164+
function getAudio(genId, callback) {
165+
const url = new URL(`${baseUrl}/generate/audio`);
166+
url.searchParams.append("generation_id", genId);
167+
168+
const options = {
169+
method: "GET",
170+
headers: {
171+
"Authorization": `Bearer ${apiKey}`,
172+
"Content-Type": "application/json",
173+
},
174+
};
175+
176+
const req = https.request(url, options, (res) => {
177+
let body = "";
178+
res.on("data", (chunk) => body += chunk);
179+
res.on("end", () => {
180+
const parsed = JSON.parse(body);
181+
callback(parsed);
182+
});
183+
});
184+
185+
req.on("error", (err) => console.error("Request error:", err));
186+
req.end();
187+
}
188+
189+
// Initiates sound generation and checks the status every 10 seconds until completion or timeout
190+
function main() {
191+
generateAudio((genResponse) => {
192+
if (!genResponse || !genResponse.id) {
193+
console.error("No generation ID received.");
194+
return;
195+
}
196+
197+
const genId = genResponse.id;
198+
console.log("Generation ID:", genId);
199+
200+
const timeout = 1000 * 1000; // 1000 sec
201+
const interval = 10 * 1000; // 10 sec
202+
const startTime = Date.now();
203+
204+
const checkStatus = () => {
205+
if (Date.now() - startTime >= timeout) {
206+
console.log("Timeout reached. Stopping.");
207+
return;
208+
}
209+
210+
getAudio(genId, (responseData) => {
211+
if (!responseData) {
212+
console.error("Error: No response from API");
213+
return;
214+
}
215+
216+
const status = responseData.status;
217+
218+
if (["waiting", "queued", "generating"].includes(status)) {
219+
console.log(`Status: ${status}. Checking again in 10 seconds.`);
220+
setTimeout(checkStatus, interval);
221+
} else {
222+
console.log("Processing complete:\n", responseData);
223+
}
224+
});
225+
};
226+
checkStatus();
227+
})
228+
}
229+
230+
main();
231+
```
232+
{% endcode %}
233+
{% endtab %}
234+
{% endtabs %}
235+
236+
<details>
237+
238+
<summary>Response</summary>
239+
240+
{% code overflow="wrap" %}
241+
```json5
242+
Generation ID: ed58c4e0-2ed6-429f-91a1-b2c13a89ff46:stable-audio
243+
Status: queued. Checking again in 10 seconds.
244+
Status: generating. Checking again in 10 seconds.
245+
Status: generating. Checking again in 10 seconds.
246+
Status: generating. Checking again in 10 seconds.
247+
Processing complete:
248+
{
249+
id: 'ed58c4e0-2ed6-429f-91a1-b2c13a89ff46:stable-audio',
250+
status: 'completed',
251+
audio_file: {
252+
url: 'https://cdn.aimlapi.com/flamingo/files/b/0a88448e/wxI96EIL4Noe21Zt3XsFc_tmpdwdfh537.wav',
253+
content_type: 'application/octet-stream',
254+
file_name: 'tmpdwdfh537.wav',
255+
file_size: 5292078
256+
}
257+
}
258+
```
259+
{% endcode %}
260+
261+
</details>
262+
263+
Listen to the track we generated:
264+
265+
{% embed url="https://drive.google.com/file/d/178CN92wTCsgeb-JiPuXiEFgZa_jonjB_/view" %}

0 commit comments

Comments
 (0)