├── apikey.txt ├── requirements.txt ├── workflow.png ├── install_req.bat ├── README.md ├── __init__.py ├── tool.py ├── ZhipuAI_GPT.py └── zhipuAi.py /apikey.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | zhipuai 2 | openpyxl -------------------------------------------------------------------------------- /workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StartHua/Comfyui_CXH_ZhipuAI/HEAD/workflow.png -------------------------------------------------------------------------------- /install_req.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | set SCRIPT_DIR=%~dp0 4 | 5 | cd /d "%SCRIPT_DIR%../../../python_embeded" 6 | 7 | python.exe -m pip install -r "%SCRIPT_DIR%requirements.txt" 8 | 9 | pause 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Comfyui_ZhipuAI 2 | 功能:文生文,文生图,图生文(反推),文生视频,图生视频 3 | 4 | 免费:GLM-4V-Flash 模型 5 | 6 | 1.安装依赖(注意zhipuai 版本需要最新) 7 | 8 | 2.apikey填写到apikey.txt 支持多个key轮询部分解决限制 申请地址:https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D 9 | 10 | 3.文生文 11 | 12 | ![688b084199ad2a941b85b7c1e3bd91d](https://github.com/user-attachments/assets/70837834-a82d-4a36-95a7-5fea70f31887) 13 | 14 | 4.文生图 15 | 16 | ![edfb8977ffc8d69a6b796459028fac1](https://github.com/user-attachments/assets/9a6edab9-6f3a-419e-bcc7-4f77d3993cb5) 17 | 18 | 5.图生文 19 | 20 | ![7b64e01f1d13153ab32ab8ffbfe718f](https://github.com/user-attachments/assets/3af262f8-e5c1-4ef8-8a21-efdf8b407513) 21 | 22 | 6.文生视频 23 | 24 | ![e3ae4fbecacb803968a993299eb3335](https://github.com/user-attachments/assets/24b14905-3da2-4308-838c-bbd7db031d10) 25 | 26 | 7.图生视频 27 | 28 | ![8c8f94c087a0c542666b135d5b67a63](https://github.com/user-attachments/assets/c65171d2-8cad-4e33-8d3f-53bd62927121) 29 | 30 | 8.支持批量生成excel: 31 | 32 | ![ae7c53259145e6cf0a5ea442ebd915a](https://github.com/StartHua/Comfyui_CXH_ZhipuAI/assets/22284244/e8da2cd8-19bf-4825-9047-51afbca1b95e) 33 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .ZhipuAI_GPT import ZhipuAI_batch_trigger 3 | from .zhipuAi import CXH_ZhiPuAi_Vision,CXH_ZhiPuAi_TX,CXH_ZhiPuAi_Cogview,CXH_ZhiPuAi_Retrieve_Video,CXH_ZhiPuAi_TX_Video,CXH_ZhiPuAi_Img_Video 4 | # A dictionary that contains all nodes you want to export with their names 5 | # NOTE: names should be globally unique 6 | NODE_CLASS_MAPPINGS = { 7 | "ZhipuAI_batch_trigger":ZhipuAI_batch_trigger, 8 | "CXH_ZhiPuAi_Vision":CXH_ZhiPuAi_Vision, 9 | "CXH_ZhiPuAi_TX":CXH_ZhiPuAi_TX, 10 | "CXH_ZhiPuAi_Cogview":CXH_ZhiPuAi_Cogview, 11 | "CXH_ZhiPuAi_TX_Video":CXH_ZhiPuAi_TX_Video, 12 | "CXH_ZhiPuAi_Retrieve_Video":CXH_ZhiPuAi_Retrieve_Video, 13 | "CXH_ZhiPuAi_Img_Video":CXH_ZhiPuAi_Img_Video 14 | } 15 | 16 | # A dictionary that contains the friendly/humanly readable titles for the nodes 17 | NODE_DISPLAY_NAME_MAPPINGS = { 18 | "CXH_ZhiPuAi_Vision":"CXH_ZhiPuAi_Vision", 19 | "CXH_ZhiPuAi_TX":"CXH_ZhiPuAi_TX", 20 | "ZhipuAI_batch_trigger":"ZhipuAI_batch_trigger", 21 | "CXH_ZhiPuAi_Cogview":"CXH_ZhiPuAi_Cogview", 22 | "CXH_ZhiPuAi_TX_Video":"CXH_ZhiPuAi_TX_Video", 23 | "CXH_ZhiPuAi_Retrieve_Video":"CXH_ZhiPuAi_Retrieve_Video", 24 | "CXH_ZhiPuAi_Img_Video":"CXH_ZhiPuAi_Img_Video" 25 | } 26 | -------------------------------------------------------------------------------- /tool.py: -------------------------------------------------------------------------------- 1 | from zhipuai import ZhipuAI 2 | 3 | import folder_paths 4 | import os 5 | import base64 6 | 7 | from PIL import Image,ImageOps, ImageFilter 8 | import numpy as np 9 | import io 10 | import requests 11 | from io import BytesIO 12 | import torch 13 | 14 | current_folder = os.path.dirname(os.path.abspath(__file__)) 15 | apiKeyFile = os.path.join(current_folder,"apiKey.txt") 16 | 17 | def get_key(): 18 | try: 19 | config_path = os.path.join(current_folder, 'apikey.txt') 20 | # 读取整个文件内容 21 | with open(config_path, 'r', encoding='utf-8') as file: 22 | content = file.read().strip() 23 | return content 24 | except: 25 | print("Error: Gemini API key is required") 26 | return "" 27 | 28 | def tensor2pil(t_image: torch.Tensor) -> Image: 29 | return Image.fromarray(np.clip(255.0 * t_image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) 30 | 31 | def pil2tensor(image:Image) -> torch.Tensor: 32 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) 33 | 34 | # 获取网络图片 35 | def img_from_url(url): 36 | # 发送HTTP请求获取图片 37 | response = requests.get(url) 38 | response.raise_for_status() # 如果请求失败,这会抛出异常 39 | # 将响应内容作为BytesIO对象打开,以便PIL可以读取它 40 | image = Image.open(BytesIO(response.content)) 41 | return image 42 | 43 | # 获取所有图片文件路径 44 | def get_all_image_paths(directory): 45 | image_paths = [] 46 | for root, dirs, files in os.walk(directory): 47 | for file in files: 48 | if file.lower().endswith(('.png', '.jpg', '.jpeg')): 49 | image_paths.append(os.path.join(root, file)) 50 | return image_paths 51 | 52 | # 将图片转换为Base64编码 53 | def image_to_base64(image_path): 54 | with open(image_path, 'rb') as image_file: 55 | return base64.b64encode(image_file.read()).decode('utf-8') 56 | 57 | # 保存分析结果到txt文件 58 | def save_to_txt(file_name, content): 59 | txt_file_path = os.path.splitext(file_name)[0] + '.txt' 60 | with open(txt_file_path, 'w', encoding='utf-8') as txt_file: 61 | txt_file.write(content) 62 | print(f"文件 {txt_file_path} 已保存。") 63 | 64 | def tensor2pil(image): 65 | return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) 66 | 67 | # pil转64 68 | def pilTobase64(pil_image): 69 | 70 | byte_arr = io.BytesIO() 71 | pil_image.save(byte_arr, format='PNG') 72 | byte_arr = byte_arr.getvalue() 73 | 74 | image_base64 = base64.b64encode(byte_arr).decode('utf-8') 75 | return image_base64 -------------------------------------------------------------------------------- /ZhipuAI_GPT.py: -------------------------------------------------------------------------------- 1 | import os 2 | import base64 3 | import numpy as np 4 | from PIL import Image,ImageOps, ImageFilter 5 | 6 | import io 7 | from zhipuai import ZhipuAI 8 | 9 | import folder_paths 10 | 11 | from openpyxl import Workbook 12 | from openpyxl.drawing.image import Image as ExcelImage 13 | 14 | from .tool import * 15 | 16 | 17 | # 打标并保存结果 18 | def start_tags(file_dir,client,prompt,saveExcel = False): 19 | image_paths = get_all_image_paths(file_dir) 20 | for image_path in image_paths: 21 | # 检查对应的txt文件是否已存在,如果存在则跳过打标 22 | txt_file_path = os.path.splitext(image_path)[0] + '.txt' 23 | if os.path.exists(txt_file_path): 24 | print(f"文件 {txt_file_path} 已存在,跳过打标。") 25 | continue 26 | 27 | print(image_path, '开始打标') 28 | image_base64 = image_to_base64(image_path) 29 | response = client.chat.completions.create( 30 | model="glm-4v", # 填写需要调用的模型名称 31 | messages=[ 32 | {"role": "user", 33 | "content": [ 34 | { 35 | "type": "text", 36 | "text": prompt 37 | }, 38 | { 39 | "type": "image_url", 40 | "image_url": { 41 | "url": image_base64 42 | } 43 | } 44 | ] 45 | }, 46 | ], 47 | ) 48 | print(image_path, '打标结束') 49 | content = response.choices[0].message.content 50 | print(content) 51 | save_to_txt(image_path, content) 52 | if saveExcel ==True: 53 | # 属性:name image prompt 54 | # 创建新的Excel工作簿和工作表 55 | wbname = "prompts" 56 | wb = Workbook() 57 | ws = wb.active 58 | ws.title = wbname 59 | # 写入表头 60 | ws.append(["name", "image", "prompt"]) 61 | width_row = 30 62 | # 设置列宽 63 | ws.column_dimensions['A'].width = width_row 64 | ws.column_dimensions['B'].width = width_row +10 65 | ws.column_dimensions['C'].width = 100 66 | # 初始化行号,从2开始因为表头占据了第一行 67 | row_number = 2 68 | # 获取所有文件 69 | files = os.listdir(file_dir) 70 | 71 | # 筛选出图片和对应的文本文件 72 | images = [f for f in files if f.endswith(('.png', '.jpg', '.jpeg'))] 73 | for image_name in images: 74 | # 构建对应的文本文件名 75 | txt_name = os.path.splitext(image_name)[0] + '.txt' 76 | txt_path = os.path.join(file_dir, txt_name) 77 | image_path = os.path.join(file_dir, image_name) 78 | # 读取文本文件内容 79 | prompt = "" 80 | if os.path.exists(txt_path): 81 | with open(txt_path, 'r', encoding='utf-8') as file: 82 | prompt = file.read() 83 | 84 | # 添加行到Excel 85 | ws.append([image_name, "", prompt]) 86 | # 将图片也插入到Excel中 87 | img = ExcelImage(image_path) 88 | img.anchor = f'B{row_number}' # 设置图片插入的位置 89 | 90 | # 设置图片缩放 91 | original_img_height = Image.open(image_path).height 92 | scale_factor = 128 / original_img_height 93 | img.height = 128 # 设置图片高度为128像素 94 | img.width = int(Image.open(image_path).width * scale_factor) # 调整宽度以保持比例 95 | 96 | ws.add_image(img) 97 | 98 | # 设置行高适配图片高度,Excel中的行高单位是点 99 | ws.row_dimensions[row_number].height = img.height * 0.75 100 | 101 | # 更新行号 102 | row_number += 1 103 | # 保存工作簿 104 | print("保存成功!") 105 | savepath = os.path.join(file_dir,wbname+".xlsx") 106 | wb.save(savepath) 107 | 108 | # 文件夹反推 109 | class ZhipuAI_batch_trigger: 110 | 111 | def __init__(self): 112 | self.client = None 113 | 114 | @classmethod 115 | def INPUT_TYPES(s): 116 | return { 117 | "required": { 118 | "inputDir": ("STRING", {"multiline": False, "default": ""},), 119 | "prompt": ("STRING", {"multiline": True, "default": "请用英文详细描述这张图像,不要使用任何中文。"},), 120 | "saveExcel": ("BOOLEAN", {"default": False}), 121 | } 122 | } 123 | 124 | RETURN_TYPES = ("STRING",) 125 | RETURN_NAMES = ("out",) 126 | FUNCTION = "gen" 127 | OUTPUT_NODE = False 128 | CATEGORY = "CXH" 129 | 130 | def gen(self, inputDir:str,prompt:str,saveExcel:bool): 131 | 132 | content = get_key() 133 | self.index = 0 134 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 135 | if self.client == None: 136 | self.client = ZhipuAI(api_key=self.keys[0]) 137 | 138 | 139 | start_tags(inputDir,self.client,prompt,saveExcel ) 140 | return(inputDir,) 141 | -------------------------------------------------------------------------------- /zhipuAi.py: -------------------------------------------------------------------------------- 1 | from .tool import * 2 | import time 3 | 4 | # 文字 5 | class CXH_ZhiPuAi_TX: 6 | 7 | def __init__(self): 8 | content = get_key() 9 | self.index = 0 10 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 11 | 12 | @classmethod 13 | def INPUT_TYPES(s): 14 | return { 15 | "required": { 16 | "model": (["glm-4-flash","glm-4-plus","glm-4", "glm-4-0520","glm-4-air","glm-4-flashx","glm-4-long","glm-4-airx"],), 17 | "system":("STRING", {"multiline": True, "default": "你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"},), 18 | "prompt":("STRING", {"multiline": True, "default": ""},), 19 | } 20 | } 21 | 22 | RETURN_TYPES = ("STRING",) 23 | RETURN_NAMES = ("out",) 24 | FUNCTION = "gen" 25 | OUTPUT_NODE = False 26 | CATEGORY = "CXH/gemini" 27 | 28 | def gen(self,model,system,prompt): 29 | if len(self.keys) ==0 : 30 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 31 | if prompt == None or prompt == "" or prompt == "": 32 | prompt = "" 33 | return ("",) 34 | #key 35 | if self.index >= len(self.keys): 36 | self.index = 0 37 | apikey = self.keys[self.index] 38 | client = ZhipuAI(api_key=apikey) 39 | self.index = self.index + 1 40 | 41 | response = client.chat.completions.create( 42 | model=model, # 填写需要调用的模型编码 43 | messages=[ 44 | {"role": "system", "content": system}, 45 | {"role": "user", "content": prompt} 46 | ], 47 | ) 48 | print(response) 49 | # 将结果列表中的张量连接在一起 50 | return (response.choices[0].message.content,) 51 | 52 | # 单个图片反推 53 | class CXH_ZhiPuAi_Vision: 54 | def __init__(self): 55 | content = get_key() 56 | self.index = 0 57 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 58 | # self.client = ZhipuAI(api_key=self.api_key) 59 | 60 | @classmethod 61 | def INPUT_TYPES(s): 62 | return { 63 | "required": { 64 | "image": ("IMAGE",), 65 | "model": (["glm-4v-flash","glm-4v-plus", "glm-4v"],), 66 | "prompt": ("STRING", {"multiline": True, "default": "请用英文详细描述这张图像,不要使用任何中文。英文输出。"},), 67 | } 68 | } 69 | 70 | RETURN_TYPES = ("STRING",) 71 | RETURN_NAMES = ("out",) 72 | FUNCTION = "gen" 73 | OUTPUT_NODE = False 74 | CATEGORY = "CXH" 75 | 76 | def gen(self, image,model,prompt:str): 77 | 78 | pil_image = tensor2pil(image) 79 | 80 | image_base64 = pilTobase64(pil_image) 81 | 82 | if len(self.keys) ==0 : 83 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 84 | 85 | #key 86 | if self.index >= len(self.keys): 87 | self.index = 0 88 | apikey = self.keys[self.index] 89 | client = ZhipuAI(api_key=apikey) 90 | self.index = self.index + 1 91 | 92 | response = client.chat.completions.create( 93 | model=model, # 填写需要调用的模型名称 94 | messages=[ 95 | {"role": "user", 96 | "content": [ 97 | { 98 | "type": "text", 99 | "text": prompt 100 | }, 101 | { 102 | "type": "image_url", 103 | "image_url": { 104 | "url": image_base64 105 | } 106 | } 107 | ] 108 | }, 109 | ], 110 | ) 111 | content = response.choices[0].message.content 112 | return(content,) 113 | 114 | class CXH_ZhiPuAi_Cogview: 115 | def __init__(self): 116 | content = get_key() 117 | self.index = 0 118 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 119 | 120 | @classmethod 121 | def INPUT_TYPES(s): 122 | return { 123 | "required": { 124 | "model": (["cogview-3-plus","cogview-3"],), 125 | "prompt": ("STRING", {"multiline": True, "default": "a girl"},), 126 | "size":(["1024x1024","768x1344","864x1152","1344x768","1152x864","1440x720","720x1440"],), 127 | "seed": ("INT", {"default": 656545, "min": 0, "max": 1000000}), 128 | } 129 | } 130 | 131 | RETURN_TYPES = ("IMAGE",) 132 | RETURN_NAMES = ("out",) 133 | FUNCTION = "gen" 134 | OUTPUT_NODE = False 135 | CATEGORY = "CXH" 136 | 137 | def gen(self, model,prompt:str,size,seed): 138 | 139 | if len(self.keys) ==0 : 140 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 141 | 142 | #key 143 | if self.index >= len(self.keys): 144 | self.index = 0 145 | apikey = self.keys[self.index] 146 | client = ZhipuAI(api_key=apikey) 147 | self.index = self.index + 1 148 | 149 | response = client.images.generations( 150 | model=model, #填写需要调用的模型编码 151 | prompt=prompt, 152 | size=size 153 | ) 154 | 155 | url = response.data[0].url 156 | 157 | image2 = img_from_url(url) 158 | image2 = pil2tensor(image2) 159 | 160 | return(image2,) 161 | 162 | # 视频 163 | class CXH_ZhiPuAi_TX_Video: 164 | def __init__(self): 165 | content = get_key() 166 | self.index = 0 167 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 168 | 169 | @classmethod 170 | def INPUT_TYPES(s): 171 | return { 172 | "required": { 173 | "model": (["cogvideox"],), 174 | "prompt": ("STRING", {"multiline": True, "default": "比得兔开小汽车,游走在马路上,脸上的表情充满开心喜悦。"},), 175 | "quality": (["quality","speed"],), 176 | "with_audio": ("BOOLEAN", {"default": True}), 177 | "seed": ("INT", {"default": 656545, "min": 0, "max": 1000000}), 178 | } 179 | } 180 | 181 | RETURN_TYPES = ("STRING",) 182 | RETURN_NAMES = ("out",) 183 | FUNCTION = "gen" 184 | OUTPUT_NODE = False 185 | CATEGORY = "CXH" 186 | 187 | def gen(self, model,prompt,quality,with_audio,seed): 188 | 189 | if len(self.keys) ==0 : 190 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 191 | 192 | #key 193 | if self.index >= len(self.keys): 194 | self.index = 0 195 | apikey = self.keys[self.index] 196 | client = ZhipuAI(api_key=apikey) 197 | self.index = self.index + 1 198 | 199 | response = client.videos.generations( 200 | model=model, 201 | prompt=prompt, 202 | quality = quality, 203 | with_audio=with_audio 204 | ) 205 | id = response.id 206 | print(id) 207 | return(id,) 208 | 209 | class CXH_ZhiPuAi_Img_Video: 210 | def __init__(self): 211 | content = get_key() 212 | self.index = 0 213 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 214 | 215 | @classmethod 216 | def INPUT_TYPES(s): 217 | return { 218 | "required": { 219 | "image": ("IMAGE",), 220 | "model": (["cogvideox"],), 221 | "prompt": ("STRING", {"multiline": True, "default": "让画面动起来"},), 222 | "size":(["720x480","1024x1024","1280x960","960x1280","1920x1080","1080x1920","2048x1080","3840x2160"],), 223 | "quality": (["quality","speed"],), 224 | "with_audio": ("BOOLEAN", {"default": True}), 225 | "duration": ("INT", {"default": 5, "min": 1, "max": 1024}), 226 | "fps": ("INT", {"default": 30, "min": 1, "max": 120}), 227 | 228 | "seed": ("INT", {"default": 656545, "min": 0, "max": 1000000}), 229 | } 230 | } 231 | 232 | RETURN_TYPES = ("STRING",) 233 | RETURN_NAMES = ("out",) 234 | FUNCTION = "gen" 235 | OUTPUT_NODE = False 236 | CATEGORY = "CXH" 237 | 238 | def gen(self, image,model,prompt,size,quality,with_audio,duration,fps,seed): 239 | 240 | if len(self.keys) ==0 : 241 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 242 | 243 | 244 | #key 245 | if self.index >= len(self.keys): 246 | self.index = 0 247 | apikey = self.keys[self.index] 248 | client = ZhipuAI(api_key=apikey) 249 | self.index = self.index + 1 250 | 251 | pil_image = tensor2pil(image) 252 | 253 | image_base64 = pilTobase64(pil_image) 254 | 255 | 256 | # 调用视频生成接口 257 | response = client.videos.generations( 258 | model=model, # 使用的视频生成模型 259 | image_url=image_base64, # 提供的图片URL地址或者 Base64 编码 260 | prompt=prompt, 261 | quality=quality, # 输出模式,"quality"为质量优先,"speed"为速度优先 262 | with_audio=with_audio, 263 | size=size, # 视频分辨率,支持最高4K(如: "3840x2160") 264 | duration=duration, # 视频时长,可选5秒或10秒 265 | fps=fps, # 帧率,可选为30或60 266 | ) 267 | 268 | id = response.id 269 | print(id) 270 | return(id,) 271 | 272 | 273 | 274 | class CXH_ZhiPuAi_Retrieve_Video: 275 | def __init__(self): 276 | content = get_key() 277 | self.index = 0 278 | self.keys = [key.strip() for key in content.split('\n') if key.strip()] 279 | 280 | @classmethod 281 | def INPUT_TYPES(s): 282 | return { 283 | "required": { 284 | "id": ("STRING", {"multiline": False, "default": "","forceInput": True},), 285 | "delay":("INT", {"default": 10}), 286 | "second":("INT", {"default": 5}), 287 | "repeat":("INT", {"default": 40}), 288 | "seed": ("INT", {"default": 656545, "min": 0, "max": 1000000}), 289 | } 290 | } 291 | 292 | RETURN_TYPES = ("IMAGE","STRING") 293 | RETURN_NAMES = ("image","video_url") 294 | FUNCTION = "gen" 295 | OUTPUT_NODE = False 296 | CATEGORY = "CXH" 297 | 298 | def gen(self, id,delay,second,repeat,seed): 299 | 300 | if len(self.keys) ==0 : 301 | print("请注册zhipuAi: https://www.bigmodel.cn/invite?icode=00e53ccPBd3LlcbyEEU8TkjPr3uHog9F4g5tjuOUqno%3D") 302 | 303 | #key 304 | if self.index >= len(self.keys): 305 | self.index = 0 306 | apikey = self.keys[self.index] 307 | client = ZhipuAI(api_key=apikey) 308 | self.index = self.index + 1 309 | 310 | print("任务id:" + id) 311 | print("等待执行任务......") 312 | time.sleep(delay) 313 | #轮询 314 | wait_req = True 315 | repeat_temp = repeat 316 | image_url = None 317 | video_url = None 318 | while wait_req: 319 | response = client.videos.retrieve_videos_result( 320 | id=id 321 | ) 322 | print(response) 323 | # 检查请求是否成功 324 | task_status = response.task_status 325 | if task_status != "SUCCESS": 326 | time.sleep(second) # 阻塞等待 327 | repeat_temp = repeat_temp - 1 328 | if repeat_temp <= 0 : 329 | wait_req = False 330 | print("轮询:" + str(repeat_temp)) 331 | else: 332 | first_result = response.video_result[0] # 获取列表的第一个元素 333 | video_url = first_result.url 334 | image_url = first_result.cover_image_url 335 | wait_req = False 336 | 337 | if image_url == None or video_url == None: 338 | print("没有获取到数据!") 339 | 340 | source_img = img_from_url(image_url) 341 | source_img = pil2tensor(source_img) 342 | 343 | return(source_img,video_url,) 344 | --------------------------------------------------------------------------------