背景
目前字節跳動公司提供了即夢AI的接口免費試用,但是并發量只有1,不過足夠我們使用了。我這里想做個使用python+tkinter實現的GUI可視化界面客戶端,這樣就不用每次都登錄官方網站去進行文生圖片,當然文生視頻,或者圖生視頻也是如此的邏輯。
實現思路
1.?編寫一個窗口
2.?窗口放置一個文本輸入框,一個按鈕和一個消息對話框就可以了
最后界面如下:
3.?給按鈕綁定事件函數,當用戶輸入文字提示詞后,點擊按鈕則生成對應的圖片
4.?獲取生成的圖片鏈接地址,然后通過打開圖片將圖片寫入對話框中?
Tkinter的python實現代碼?
import time
import tkinter
from tkinter import scrolledtext, END, RAISED
from io import BytesIO
import requests
from tttt.ai_chat import AI_chat
from PIL import Image, ImageTk
from tttt.play_voice import play_audio
from tttt.record_voice import record_audio
from tttt.streaming_asr_demo import test_one
from tttt.voice_generate import txt_to_voice
from tttt.即夢AI文生圖片 import txt_to_image# 創建根窗口
root = tkinter.Tk()
# 設置屬性
root.title('即夢AI文生圖片python客戶端')
# 設置窗口大小
root.geometry("650x560")# 文本歷史記錄
txt_history = scrolledtext.ScrolledText(root, width=80, height=30)
txt_history.tag_config('green', foreground='#008B00')
txt_history.tag_config('red', foreground='#FF0000')
txt_history.grid(column=0, row=0, columnspan=3, padx=10, pady=10)# 標簽
lbl = tkinter.Label(root, text="請輸入文字:")
lbl.grid(column=0, row=1, padx=5, pady=5)# 文本輸入框
txt_input = tkinter.Entry(root, width=50)
txt_input.grid(column=1, row=1, padx=5, pady=5)# 按鈕樣式
button_style = {"font": ("Arial", 10, "bold"), # 字體樣式"bg": "#4CAF50", # 背景顏色"fg": "white", # 文字顏色"activebackground": "#45a049", # 按鈕按下時的背景顏色"activeforeground": "white", # 按鈕按下時的文字顏色"relief": RAISED, # 按鈕邊框樣式"bd": 2, # 按鈕邊框寬度"padx": 5, # 按鈕內部水平方向的填充"pady": 5 # 按鈕內部垂直方向的填充
}# 從網頁下載圖片并加載
def download_and_display_image(url):try:response = requests.get(url)response.raise_for_status() # 確保請求成功image_data = BytesIO(response.content)image = Image.open(image_data)photo = ImageTk.PhotoImage(image)# 在歷史消息對話框中插入圖片txt_history.image = photo # 保持對PhotoImage的引用,防止被垃圾回收txt_history.insert(END, "\n")txt_history.image_create(END, image=photo)txt_history.insert(END, "\n")except requests.RequestException as e:txt_history.insert(END, f"無法下載圖片: {e}\n")# 發送文生圖片
def txt_generate_image():# 獲取輸入框文本內容user_message = txt_input.get()# 將用戶輸入的內容插入對話框中txt_history.insert(END, '即夢AI:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n','purple') # 將輸入的內容添加到文本歷史記錄中txt_history.insert(END, "正在請求處理中..." + "\n")try:# 文生圖片接口image_path = txt_to_image(user_message)if image_path:# 清空輸入框txt_input.delete(0, END)# 清空所有歷史記錄txt_history.delete("1.0", END)# 插入最新消息txt_history.insert(END, "成功生成圖片如下" + "\n")# 顯示圖片到歷史對話框中download_and_display_image(image_path)except Exception as e:txt_history.insert(END, "后臺處理失敗,原因如下:" + "\n")txt_history.insert(END, str(e) + "\n")btn = tkinter.Button(root, text="文生圖片", command=txt_generate_image, **button_style)
btn.grid(column=1, row=3, padx=5, pady=5)# 運行主窗口
root.mainloop()
火山引擎的即夢AI接口及改造
即夢AI文生圖片接口文檔
即夢AI-圖像生成--即夢AI-火山引擎
http接口示例:
import json
import sys
import os
import base64
import datetime
import hashlib
import hmac
import requestsmethod = 'POST'
host = 'visual.volcengineapi.com'
region = 'cn-north-1'
endpoint = 'https://visual.volcengineapi.com'
service = 'cv'def sign(key, msg):return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()def getSignatureKey(key, dateStamp, regionName, serviceName):kDate = sign(key.encode('utf-8'), dateStamp)kRegion = sign(kDate, regionName)kService = sign(kRegion, serviceName)kSigning = sign(kService, 'request')return kSigningdef formatQuery(parameters):request_parameters_init = ''for key in sorted(parameters):request_parameters_init += key + '=' + parameters[key] + '&'request_parameters = request_parameters_init[:-1]return request_parametersdef signV4Request(access_key, secret_key, service, req_query, req_body):if access_key is None or secret_key is None:print('No access key is available.')sys.exit()t = datetime.datetime.utcnow()current_date = t.strftime('%Y%m%dT%H%M%SZ')# current_date = '20210818T095729Z'datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scopecanonical_uri = '/'canonical_querystring = req_querysigned_headers = 'content-type;host;x-content-sha256;x-date'payload_hash = hashlib.sha256(req_body.encode('utf-8')).hexdigest()content_type = 'application/json'canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + \'\n' + 'x-content-sha256:' + payload_hash + \'\n' + 'x-date:' + current_date + '\n'canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + \'\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash# print(canonical_request)algorithm = 'HMAC-SHA256'credential_scope = datestamp + '/' + region + '/' + service + '/' + 'request'string_to_sign = algorithm + '\n' + current_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()# print(string_to_sign)signing_key = getSignatureKey(secret_key, datestamp, region, service)# print(signing_key)signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()# print(signature)authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + \credential_scope + ', ' + 'SignedHeaders=' + \signed_headers + ', ' + 'Signature=' + signature# print(authorization_header)headers = {'X-Date': current_date,'Authorization': authorization_header,'X-Content-Sha256': payload_hash,'Content-Type': content_type}# print(headers)# ************* SEND THE REQUEST *************request_url = endpoint + '?' + canonical_querystringprint('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')print('Request URL = ' + request_url)try:r = requests.post(request_url, headers=headers, data=req_body)except Exception as err:print(f'error occurred: {err}')raiseelse:print('\nRESPONSE++++++++++++++++++++++++++++++++++++')print(f'Response code: {r.status_code}\n')# 使用 replace 方法將 \u0026 替換為 &resp_str = r.text.replace("\\u0026", "&")print(f'Response body: {resp_str}\n')if __name__ == "__main__":# 請求憑證,從訪問控制申請access_key = 'AK*****'secret_key = '*****=='# 請求Query,按照接口文檔中填入即可query_params = {'Action': 'CVProcess','Version': '2022-08-31',}formatted_query = formatQuery(query_params)# 請求Body,按照接口文檔中填入即可body_params = {"req_key": "******",# ......}formatted_body = json.dumps(body_params)signV4Request(access_key, secret_key, service,formatted_query, formatted_body)
這里要求我們開通服務,并創建對應的AK和SK
賬號登錄-火山引擎歡迎登錄火山引擎,火山引擎是字節跳動旗下的云服務平臺。https://console.volcengine.com/ai/ability/info/104
賬號登錄-火山引擎
這里我已經開通了,自行選擇開通試用就行,不需要點擊正式調用,不然收費
?
接口改造
原來的接口只能查看是否調用成功,我們想獲取圖片地址,并將圖片顯示在對話框中,因此需要獲取返回值,請求體里面加了"return_url":True,就是用來獲取圖片地址的。同時將認證的AK和SK也填充到自定義函數中,這樣接口地址可以正常使用認證并返回我們要的結果。
import json
import sys
import os
import base64
import datetime
import hashlib
import hmac
import requestsmethod = 'POST'
host = 'visual.volcengineapi.com'
region = 'cn-north-1'
endpoint = 'https://visual.volcengineapi.com'
service = 'cv'def sign(key, msg):return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()def getSignatureKey(key, dateStamp, regionName, serviceName):kDate = sign(key.encode('utf-8'), dateStamp)kRegion = sign(kDate, regionName)kService = sign(kRegion, serviceName)kSigning = sign(kService, 'request')return kSigningdef formatQuery(parameters):request_parameters_init = ''for key in sorted(parameters):request_parameters_init += key + '=' + parameters[key] + '&'request_parameters = request_parameters_init[:-1]return request_parametersdef signV4Request(access_key, secret_key, service, req_query, req_body):if access_key is None or secret_key is None:print('No access key is available.')sys.exit()t = datetime.datetime.utcnow()current_date = t.strftime('%Y%m%dT%H%M%SZ')# current_date = '20210818T095729Z'datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scopecanonical_uri = '/'canonical_querystring = req_querysigned_headers = 'content-type;host;x-content-sha256;x-date'payload_hash = hashlib.sha256(req_body.encode('utf-8')).hexdigest()content_type = 'application/json'canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + \'\n' + 'x-content-sha256:' + payload_hash + \'\n' + 'x-date:' + current_date + '\n'canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + \'\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash# print(canonical_request)algorithm = 'HMAC-SHA256'credential_scope = datestamp + '/' + region + '/' + service + '/' + 'request'string_to_sign = algorithm + '\n' + current_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()# print(string_to_sign)signing_key = getSignatureKey(secret_key, datestamp, region, service)# print(signing_key)signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()# print(signature)authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + \credential_scope + ', ' + 'SignedHeaders=' + \signed_headers + ', ' + 'Signature=' + signature# print(authorization_header)headers = {'X-Date': current_date,'Authorization': authorization_header,'X-Content-Sha256': payload_hash,'Content-Type': content_type}# print(headers)# ************* SEND THE REQUEST *************request_url = endpoint + '?' + canonical_querystringprint('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')# print('Request URL = ' + request_url)try:r = requests.post(request_url, headers=headers, data=req_body)except Exception as err:print(f'error occurred: {err}')raiseelse:# print('\nRESPONSE++++++++++++++++++++++++++++++++++++')print(f'Response code: {r.status_code}\n')# 注釋調原來的返回處理,我們不需要文本類型的,我們需要json格式的# 使用 replace 方法將 \u0026 替換為 &# resp_str = r.text.replace("\\u0026", "&")# print(f'Response body: {resp_str}\n')# 獲取json類型的返回對象,可進行數據處理,獲取返回的image_urlprint(r.json()['data']['image_urls'][0])return r.json()['data']['image_urls'][0]def txt_to_image(prompt_text):# 請求憑證,從訪問控制申請access_key = ''secret_key = ''# 請求Query,按照接口文檔中填入即可query_params = {'Action': 'CVProcess','Version': '2022-08-31',}formatted_query = formatQuery(query_params)# 請求Body,按照接口文檔中填入即可body_params = {"req_key": "jimeng_high_aes_general_v21_L","prompt": prompt_text,"return_url": True}formatted_body = json.dumps(body_params)image_url = signV4Request(access_key, secret_key, service,formatted_query, formatted_body)return image_urlif __name__ == "__main__":txt_to_image('一張海報,上面文字寫著:"新年快樂"')
請求的body體兩個參數必填,因此在body_params中必須放置,其中req_key取固定值,prompt就是我們的輸入框中的文本提示詞。
測試結果:
到這里就大功告成了!可以愉快的玩耍了?