Skip to content

Commit c19f505

Browse files
techpro-aimlapigitbook-bot
authored andcommitted
GITBOOK-780: docs: add manual examples for old klings 1 and 1.6
1 parent ac0aab0 commit c19f505

11 files changed

Lines changed: 1840 additions & 139 deletions

docs/api-references/video-models/Kling-AI/v1-pro-image-to-video.md

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,214 @@ If the video generation task status is `completed`, the response will include th
6060
{% openapi-operation spec="universal-video-endpoint-fetch" path="/v2/video/generations" method="get" %}
6161
[OpenAPI universal-video-endpoint-fetch](https://raw.githubusercontent.com/aimlapi/api-docs/refs/heads/main/docs/api-references/video-models/universal-video-fetch.json)
6262
{% endopenapi-operation %}
63+
64+
## Full Example: Generating and Retrieving the Video From the Server
65+
66+
We have a classic [reproduction](https://s2-111386.kwimgs.com/bs2/mmu-aiplatform-temp/kling/20240620/1.jpeg) of the famous da Vinci painting. Let's ask the model to generate a video where the Mona Lisa puts on glasses. The code below creates a video generation task, then automatically polls the server every **15** seconds until it finally receives the video URL.
67+
68+
{% tabs %}
69+
{% tab title="Python" %}
70+
{% code overflow="wrap" %}
71+
```python
72+
import requests
73+
import time
74+
75+
# Insert your AIML API Key instead of <YOUR_AIMLAPI_KEY>:
76+
api_key = "<YOUR_AIMLAPI_KEY>"
77+
base_url = "https://api.aimlapi.com/v2"
78+
79+
# Creating and sending a video generation task to the server
80+
def generate_video():
81+
url = f"{base_url}/video/generations"
82+
headers = {
83+
"Authorization": f"Bearer {api_key}",
84+
}
85+
86+
data = {
87+
"model": "kling-video/v1/pro/image-to-video",
88+
"prompt": "Mona Lisa puts on glasses with her hands.",
89+
"image_url": "https://raw.githubusercontent.com/aimlapi/api-docs/main/reference-files/mona_lisa_extended.jpg",
90+
"duration": "5",
91+
}
92+
93+
response = requests.post(url, json=data, headers=headers)
94+
95+
if response.status_code >= 400:
96+
print(f"Error: {response.status_code} - {response.text}")
97+
else:
98+
response_data = response.json()
99+
return response_data
100+
101+
# Requesting the result of the task from the server using the generation_id
102+
def get_video(gen_id):
103+
url = f"{base_url}/video/generations"
104+
params = {
105+
"generation_id": gen_id,
106+
}
107+
108+
headers = {
109+
"Authorization": f"Bearer {api_key}",
110+
"Content-Type": "application/json"
111+
}
112+
113+
response = requests.get(url, params=params, headers=headers)
114+
return response.json()
115+
116+
117+
def main():
118+
# Running video generation and getting a task id
119+
gen_response = generate_video()
120+
gen_id = gen_response.get("id")
121+
print("Generation ID: ", gen_id)
122+
123+
# Try to retrieve the video from the server every 15 sec
124+
if gen_id:
125+
start_time = time.time()
126+
127+
timeout = 1000 # 1000 sec = 16 min 40 sec
128+
while time.time() - start_time < timeout:
129+
response_data = get_video(gen_id)
130+
131+
if response_data is None:
132+
print("Error: No response from API")
133+
break
134+
135+
status = response_data.get("status")
136+
137+
if status in ["queued", "generating"]:
138+
print(f"Status: {status}. Checking again in 15 seconds.")
139+
time.sleep(15)
140+
else:
141+
print("Processing complete:\n", response_data)
142+
return response_data
143+
144+
print("Timeout reached. Stopping.")
145+
return None
146+
147+
148+
if __name__ == "__main__":
149+
main()
150+
```
151+
{% endcode %}
152+
{% endtab %}
153+
154+
{% tab title="JavaScript" %}
155+
{% code overflow="wrap" %}
156+
```javascript
157+
const https = require("https");
158+
const { URL } = require("url");
159+
160+
// Replace <YOUR_AIMLAPI_KEY> with your actual AI/ML API key
161+
const apiKey = "<YOUR_AIMLAPI_KEY>";
162+
const baseUrl = "https://api.aimlapi.com/v2";
163+
164+
// Creating and sending a video generation task to the server
165+
function generateVideo(callback) {
166+
const data = JSON.stringify({
167+
model: "kling-video/v1/pro/image-to-video",
168+
prompt: "Mona Lisa puts on glasses with her hands.",
169+
image_url: "https://raw.githubusercontent.com/aimlapi/api-docs/main/reference-files/mona_lisa_extended.jpg",
170+
duration: "5",
171+
});
172+
173+
const url = new URL(`${baseUrl}/video/generations`);
174+
const options = {
175+
method: "POST",
176+
headers: {
177+
"Authorization": `Bearer ${apiKey}`,
178+
"Content-Type": "application/json",
179+
"Content-Length": Buffer.byteLength(data),
180+
},
181+
};
182+
183+
const req = https.request(url, options, (res) => {
184+
let body = "";
185+
res.on("data", (chunk) => body += chunk);
186+
res.on("end", () => {
187+
if (res.statusCode >= 400) {
188+
console.error(`Error: ${res.statusCode} - ${body}`);
189+
callback(null);
190+
} else {
191+
const parsed = JSON.parse(body);
192+
callback(parsed);
193+
}
194+
});
195+
});
196+
197+
req.on("error", (err) => console.error("Request error:", err));
198+
req.write(data);
199+
req.end();
200+
}
201+
202+
// Requesting the result of the task from the server using the generation_id
203+
function getVideo(genId, callback) {
204+
const url = new URL(`${baseUrl}/video/generations`);
205+
url.searchParams.append("generation_id", genId);
206+
207+
const options = {
208+
method: "GET",
209+
headers: {
210+
"Authorization": `Bearer ${apiKey}`,
211+
"Content-Type": "application/json",
212+
},
213+
};
214+
215+
const req = https.request(url, options, (res) => {
216+
let body = "";
217+
res.on("data", (chunk) => body += chunk);
218+
res.on("end", () => {
219+
const parsed = JSON.parse(body);
220+
callback(parsed);
221+
});
222+
});
223+
224+
req.on("error", (err) => console.error("Request error:", err));
225+
req.end();
226+
}
227+
228+
// Initiates video generation and checks the status every 15 seconds until completion or timeout
229+
function main() {
230+
generateVideo((genResponse) => {
231+
if (!genResponse || !genResponse.id) {
232+
console.error("No generation ID received.");
233+
return;
234+
}
235+
236+
const genId = genResponse.id;
237+
console.log("Generation ID:", genId);
238+
239+
const timeout = 1000 * 1000; // 1000 sec = 16 min 40 sec
240+
const interval = 15 * 1000; // 15 sec
241+
const startTime = Date.now();
242+
243+
const checkStatus = () => {
244+
if (Date.now() - startTime >= timeout) {
245+
console.log("Timeout reached. Stopping.");
246+
return;
247+
}
248+
249+
getVideo(genId, (responseData) => {
250+
if (!responseData) {
251+
console.error("Error: No response from API");
252+
return;
253+
}
254+
255+
const status = responseData.status;
256+
257+
if (["queued", "generating"].includes(status)) {
258+
console.log(`Status: ${status}. Checking again in 15 seconds.`);
259+
setTimeout(checkStatus, interval);
260+
} else {
261+
console.log("Processing complete:\n", responseData);
262+
}
263+
});
264+
};
265+
checkStatus();
266+
})
267+
}
268+
269+
main();
270+
```
271+
{% endcode %}
272+
{% endtab %}
273+
{% endtabs %}

0 commit comments

Comments
 (0)