
DeepSeek Janus-Pro 應用代碼與圖片鏈接實踐
要使用文心AI作畫,首先需要在百度智能云平臺上注冊賬號并獲取API Key和Secret Key。這些憑證是訪問API的必要條件。
文心AI作畫API主要通過提交請求和查詢結果兩個接口實現圖像生成。
提交請求接口用于根據用戶輸入的文本生成圖像任務ID。請求信息包括文本描述、圖片分辨率及風格參數。
import requests
import json
API_KEY = "你的API Key"
SECRET_KEY = "你的Secret Key"
url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + get_access_token()
payload = json.dumps({
"text": "中國山水畫",
"resolution": "1024*1024",
"style": "古風",
"num": 2
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
查詢結果接口用于獲取圖像生成狀態及最終圖片鏈接。通過任務ID查詢,生成圖像的狀態和地址將被返回。
import requests
import json
url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=" + get_access_token()
payload = json.dumps({
"taskId": "提交請求返回的taskId"
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
文心speed模型提供了一種快速調用百度AI作畫API的方法。用戶可以通過命令行或Python代碼實現快速調用。
通過命令行調用API,需先獲取access_token,并在API調用中使用。
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'
curl -XPOST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=[access_token]' -d '{"messages": [{"role":"user","content":"介紹一下北京"}]}' | iconv -f utf-8 -t utf-8
通過Python腳本可以實現單輪或多輪對話的API調用,將access_token填入腳本中即可。
import requests
import json
def get_access_token():
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]"
response = requests.post(url).json()
return response.get("access_token")
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=" + get_access_token()
payload = json.dumps({"messages": [{"role": "user", "content": "介紹一下北京"}]})
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
在使用API時,可能會遇到一些常見錯誤,如API請求超限或欠費問題。這時需要檢查賬戶余額及API調用額度,確保在合理范圍內使用。
問:如何獲取文心AI作畫的API Key?
問:API調用遇到請求超限怎么辦?
問:生成的圖片如何下載?
通過本文的詳細介紹,您將能夠熟練使用百度文心 ERNIE-ViLG 的 API Key及相關接口,生成高質量的圖像,為創作提供更多可能性。