当前位置: 首页 > article >正文

openclaw技术实践:Nunchaku FLUX.1-dev ComfyUI批量生成脚本编写

openclaw技术实践Nunchaku FLUX.1-dev ComfyUI批量生成脚本编写你是不是也遇到过这样的场景在ComfyUI里用Nunchaku FLUX.1-dev模型生成了一张惊艳的图片然后想“要是能批量生成不同风格、不同主题的图片就好了。”但每次都要手动修改提示词、调整参数、点击运行效率实在太低。今天我就来分享一个实战技巧——如何编写ComfyUI批量生成脚本让你一次性生成几十甚至上百张高质量图片彻底解放双手。无论你是做内容创作、电商设计还是个人项目这个技能都能让你的工作效率提升10倍。1. 为什么需要批量生成脚本在深入代码之前我们先聊聊为什么手动操作行不通。想象一下你需要为新产品生成100张不同场景的营销图。手动操作意味着重复输入100次提示词调整100次参数设置点击100次“运行”按钮等待100次生成完成手动保存100张图片这不仅耗时耗力还容易出错。而脚本可以帮你一键生成准备好提示词列表脚本自动循环执行参数批量调整轻松测试不同参数组合的效果结果自动保存生成图片自动命名、分类保存无人值守运行设置好后让电脑自己跑你去喝咖啡接下来我会带你从零开始一步步构建一个实用的批量生成脚本。2. 环境与准备工作在编写脚本之前确保你的环境已经就绪。2.1 基础环境确认首先你的ComfyUI应该已经正常安装并能够运行Nunchaku FLUX.1-dev模型。如果还没完成这一步可以参考我之前写的部署指南。打开终端进入你的ComfyUI目录检查几个关键点# 确认ComfyUI目录结构 cd ~/ComfyUI ls -la # 检查custom_nodes目录下是否有nunchaku_nodes ls custom_nodes/ | grep nunchaku # 检查模型文件是否存在 ls models/unet/ | grep flux.1-dev ls models/text_encoders/ ls models/vae/如果这些都正常说明你的基础环境已经准备好。2.2 理解ComfyUI的API接口ComfyUI提供了强大的API接口允许我们通过代码控制整个生成流程。这是编写批量脚本的基础。ComfyUI默认在http://localhost:8188启动一个WebSocket服务器和一个HTTP API服务器。我们的脚本将通过这些接口获取当前的工作流配置修改工作流参数触发图片生成获取生成结果让我们先测试一下API是否正常工作import requests import json # ComfyUI的API地址 api_url http://localhost:8188 # 测试连接 try: response requests.get(f{api_url}/history) if response.status_code 200: print(✅ ComfyUI API连接成功) else: print(❌ 无法连接到ComfyUI API请检查ComfyUI是否正在运行) except Exception as e: print(f❌ 连接失败: {e})把这个测试脚本保存为test_api.py并运行如果看到成功提示说明API接口可用。3. 批量生成脚本核心实现现在进入最核心的部分——编写批量生成脚本。我会分步骤讲解确保你能完全理解。3.1 基础脚本框架我们先创建一个基础的脚本框架包含必要的功能模块#!/usr/bin/env python3 ComfyUI Nunchaku FLUX.1-dev 批量生成脚本 作者openclaw 功能批量生成图片支持自定义提示词、参数和保存路径 import requests import json import time import os from datetime import datetime from typing import List, Dict, Any import uuid class ComfyUIBatchGenerator: ComfyUI批量生成器 def __init__(self, server_address: str http://localhost:8188): 初始化批量生成器 Args: server_address: ComfyUI服务器地址 self.server_address server_address self.client_id str(uuid.uuid4()) def get_workflow(self) - Dict[str, Any]: 获取当前工作流配置 try: response requests.get(f{self.server_address}/object_info) return response.json() except Exception as e: print(f获取工作流失败: {e}) return {} def queue_prompt(self, prompt: Dict[str, Any]) - str: 提交生成任务到队列 Args: prompt: 工作流配置字典 Returns: prompt_id: 任务ID try: data {prompt: prompt, client_id: self.client_id} response requests.post( f{self.server_address}/prompt, jsondata ) result response.json() return result.get(prompt_id, ) except Exception as e: print(f提交任务失败: {e}) return def get_history(self, prompt_id: str) - Dict[str, Any]: 获取任务历史记录 Args: prompt_id: 任务ID Returns: 历史记录字典 try: response requests.get(f{self.server_address}/history/{prompt_id}) return response.json() except Exception as e: print(f获取历史记录失败: {e}) return {} def wait_for_completion(self, prompt_id: str, timeout: int 300) - bool: 等待任务完成 Args: prompt_id: 任务ID timeout: 超时时间秒 Returns: 是否成功完成 start_time time.time() while time.time() - start_time timeout: history self.get_history(prompt_id) if history and prompt_id in history: status history[prompt_id].get(status, {}) if status.get(completed, False): return True elif status.get(error, False): print(f任务执行出错: {status.get(error_message, 未知错误)}) return False time.sleep(1) # 每秒检查一次 print(f任务超时: {timeout}秒) return False def save_image(self, image_data: bytes, filename: str, output_dir: str output): 保存生成的图片 Args: image_data: 图片二进制数据 filename: 文件名 output_dir: 输出目录 # 创建输出目录 os.makedirs(output_dir, exist_okTrue) # 生成完整路径 filepath os.path.join(output_dir, filename) # 保存图片 with open(filepath, wb) as f: f.write(image_data) print(f✅ 图片已保存: {filepath}) return filepath if __name__ __main__: # 测试脚本 generator ComfyUIBatchGenerator() print(批量生成器初始化完成)这个框架包含了批量生成所需的核心功能连接API、提交任务、等待完成、保存结果。3.2 加载和修改工作流接下来我们需要加载Nunchaku FLUX.1-dev的工作流并能够动态修改参数。首先从ComfyUI导出你的工作流配置在ComfyUI网页端加载nunchaku-flux.1-dev.json工作流点击右上角的Save按钮保存为JSON文件将文件保存到脚本目录命名为flux_workflow.json然后我们添加工作流加载和修改功能class ComfyUIBatchGenerator: # ... 之前的代码 ... def load_workflow(self, workflow_path: str) - Dict[str, Any]: 从文件加载工作流配置 Args: workflow_path: 工作流JSON文件路径 Returns: 工作流配置字典 try: with open(workflow_path, r, encodingutf-8) as f: workflow json.load(f) print(f✅ 工作流加载成功: {workflow_path}) return workflow except Exception as e: print(f❌ 加载工作流失败: {e}) return {} def update_prompt_text(self, workflow: Dict[str, Any], node_id: str, text: str) - Dict[str, Any]: 更新提示词节点的文本内容 Args: workflow: 工作流配置 node_id: 节点ID text: 新的提示词文本 Returns: 更新后的工作流 if prompt in workflow: for node_id_key, node_data in workflow[prompt].items(): if inputs in node_data and text in node_data[inputs]: # 找到文本输入节点 workflow[prompt][node_id_key][inputs][text] text print(f✅ 提示词已更新: {text[:50]}...) break return workflow def update_sampler_steps(self, workflow: Dict[str, Any], node_id: str, steps: int) - Dict[str, Any]: 更新采样器的步数 Args: workflow: 工作流配置 node_id: 节点ID steps: 采样步数 Returns: 更新后的工作流 if prompt in workflow: for node_id_key, node_data in workflow[prompt].items(): if inputs in node_data and steps in node_data[inputs]: # 找到采样器节点 workflow[prompt][node_id_key][inputs][steps] steps print(f✅ 采样步数已更新: {steps}) break return workflow def update_resolution(self, workflow: Dict[str, Any], width: int, height: int) - Dict[str, Any]: 更新生成图片的分辨率 Args: workflow: 工作流配置 width: 图片宽度 height: 图片高度 Returns: 更新后的工作流 if prompt in workflow: for node_id_key, node_data in workflow[prompt].items(): # 查找空 latent 图像节点设置分辨率 if inputs in node_data and width in node_data[inputs]: workflow[prompt][node_id_key][inputs][width] width workflow[prompt][node_id_key][inputs][height] height print(f✅ 分辨率已更新: {width}x{height}) break return workflow3.3 完整的批量生成实现现在我们把所有功能整合起来创建一个完整的批量生成脚本class ComfyUIBatchGenerator: # ... 之前的代码 ... def generate_single_image(self, workflow: Dict[str, Any], prompt_text: str, output_dir: str output, image_prefix: str generated, steps: int 20, width: int 1024, height: int 1024) - str: 生成单张图片 Args: workflow: 基础工作流配置 prompt_text: 提示词 output_dir: 输出目录 image_prefix: 图片文件名前缀 steps: 采样步数 width: 图片宽度 height: 图片高度 Returns: 生成的图片路径 print(f\n 开始生成图片: {prompt_text[:50]}...) # 复制工作流以避免修改原始配置 current_workflow json.loads(json.dumps(workflow)) # 更新参数 current_workflow self.update_prompt_text(current_workflow, , prompt_text) current_workflow self.update_sampler_steps(current_workflow, , steps) current_workflow self.update_resolution(current_workflow, width, height) # 提交生成任务 prompt_id self.queue_prompt(current_workflow) if not prompt_id: print(❌ 提交任务失败) return print(f 任务ID: {prompt_id}) # 等待任务完成 if not self.wait_for_completion(prompt_id): print(❌ 任务执行失败) return # 获取生成结果 history self.get_history(prompt_id) if not history or prompt_id not in history: print(❌ 无法获取任务历史) return # 提取图片数据 outputs history[prompt_id].get(outputs, {}) image_data None for node_id, node_output in outputs.items(): if images in node_output: for image_info in node_output[images]: # 获取图片数据 image_url f{self.server_address}/view?filename{image_info[filename]}type{image_info[type]} response requests.get(image_url) if response.status_code 200: image_data response.content break if image_data: break if not image_data: print(❌ 未找到生成的图片) return # 保存图片 timestamp datetime.now().strftime(%Y%m%d_%H%M%S) filename f{image_prefix}_{timestamp}_{prompt_id[:8]}.png filepath self.save_image(image_data, filename, output_dir) return filepath def batch_generate(self, workflow_path: str, prompts: List[str], output_dir: str output, batch_prefix: str batch, steps: int 20, width: int 1024, height: int 1024) - List[str]: 批量生成图片 Args: workflow_path: 工作流文件路径 prompts: 提示词列表 output_dir: 输出目录 batch_prefix: 批次前缀 steps: 采样步数 width: 图片宽度 height: 图片高度 Returns: 生成的图片路径列表 print(f 开始批量生成共{len(prompts)}个提示词) # 加载工作流 base_workflow self.load_workflow(workflow_path) if not base_workflow: print(❌ 无法加载工作流批量生成终止) return [] # 创建批次输出目录 batch_time datetime.now().strftime(%Y%m%d_%H%M%S) batch_output_dir os.path.join(output_dir, f{batch_prefix}_{batch_time}) os.makedirs(batch_output_dir, exist_okTrue) generated_files [] # 遍历所有提示词 for i, prompt in enumerate(prompts, 1): print(f\n 处理第{i}/{len(prompts)}个提示词) try: # 生成单张图片 filepath self.generate_single_image( workflowbase_workflow, prompt_textprompt, output_dirbatch_output_dir, image_prefixfimg_{i:03d}, stepssteps, widthwidth, heightheight ) if filepath: generated_files.append(filepath) # 记录生成日志 log_entry { index: i, prompt: prompt, filepath: filepath, timestamp: datetime.now().isoformat(), steps: steps, resolution: f{width}x{height} } log_file os.path.join(batch_output_dir, generation_log.json) log_data [] if os.path.exists(log_file): with open(log_file, r, encodingutf-8) as f: log_data json.load(f) log_data.append(log_entry) with open(log_file, w, encodingutf-8) as f: json.dump(log_data, f, ensure_asciiFalse, indent2) print(f✅ 第{i}张图片生成完成) else: print(f❌ 第{i}张图片生成失败) except Exception as e: print(f❌ 处理第{i}个提示词时出错: {e}) continue # 添加短暂延迟避免服务器压力过大 if i len(prompts): time.sleep(1) print(f\n 批量生成完成共生成{len(generated_files)}张图片) print(f 输出目录: {batch_output_dir}) return generated_files # 使用示例 def main(): 批量生成示例 # 初始化生成器 generator ComfyUIBatchGenerator() # 定义提示词列表 prompts [ A beautiful sunset over mountains, digital art, vibrant colors, 8K resolution, A futuristic city at night with flying cars, cyberpunk style, neon lights, A peaceful forest with sunlight streaming through trees, fantasy art style, An astronaut floating in space with Earth in background, realistic, detailed, A cute cartoon cat wearing glasses and reading a book, anime style, An ancient temple in the jungle, overgrown with vines, mysterious atmosphere, A steampunk airship flying over Victorian London, detailed machinery, A magical library with floating books and glowing crystals, fantasy art, A underwater scene with colorful coral reef and tropical fish, realistic, A samurai warrior in cherry blossom forest, traditional Japanese art style ] # 批量生成 generated_files generator.batch_generate( workflow_pathflux_workflow.json, # 你的工作流文件路径 promptsprompts, output_dirbatch_output, batch_prefixflux_batch, steps25, # 推理步数 width1024, # 图片宽度 height1024 # 图片高度 ) print(f\n 生成统计:) print(f 成功: {len(generated_files)}张) print(f 失败: {len(prompts) - len(generated_files)}张) # 显示生成的图片路径 if generated_files: print(\n 生成的图片:) for filepath in generated_files: print(f - {os.path.basename(filepath)}) if __name__ __main__: main()4. 高级功能扩展基础批量生成已经能解决大部分需求但我们可以做得更好。下面添加一些高级功能。4.1 参数组合批量测试有时候我们需要测试不同参数组合的效果。这个功能可以帮你自动测试多种配置class AdvancedBatchGenerator(ComfyUIBatchGenerator): 高级批量生成器支持参数组合测试 def generate_with_parameter_grid(self, workflow_path: str, base_prompt: str, parameter_grid: Dict[str, List[Any]], output_dir: str parameter_test) - Dict[str, List[str]]: 使用参数网格生成图片测试不同参数组合 Args: workflow_path: 工作流文件路径 base_prompt: 基础提示词 parameter_grid: 参数网格格式如 {steps: [20, 30, 40], cfg: [7.0, 8.0, 9.0]} output_dir: 输出目录 Returns: 参数组合到图片路径的映射 print(f 开始参数网格测试) # 加载工作流 base_workflow self.load_workflow(workflow_path) if not base_workflow: return {} # 创建输出目录 test_time datetime.now().strftime(%Y%m%d_%H%M%S) test_output_dir os.path.join(output_dir, fparam_test_{test_time}) os.makedirs(test_output_dir, exist_okTrue) # 生成所有参数组合 from itertools import product param_names list(parameter_grid.keys()) param_values list(parameter_grid.values()) param_combinations list(product(*param_values)) print(f 共{len(param_combinations)}种参数组合) results {} for i, combination in enumerate(param_combinations, 1): # 创建参数描述 param_desc _.join([f{name}_{value} for name, value in zip(param_names, combination)]) prompt_with_params f{base_prompt} | Parameters: {param_desc} print(f\n 测试组合 {i}/{len(param_combinations)}: {param_desc}) # 复制工作流 current_workflow json.loads(json.dumps(base_workflow)) # 应用参数组合 # 这里需要根据实际工作流节点来更新参数 # 示例更新采样步数 if steps in parameter_grid: steps_index param_names.index(steps) current_workflow self.update_sampler_steps( current_workflow, , combination[steps_index] ) # 生成图片 try: filepath self.generate_single_image( workflowcurrent_workflow, prompt_textprompt_with_params, output_dirtest_output_dir, image_prefixfparam_{i:03d}, steps25, # 默认值会被参数覆盖 width1024, height1024 ) if filepath: results[param_desc] { filepath: filepath, parameters: dict(zip(param_names, combination)), prompt: prompt_with_params } # 保存参数配置 config_file os.path.join(test_output_dir, fparam_{i:03d}_config.json) with open(config_file, w, encodingutf-8) as f: json.dump(results[param_desc], f, ensure_asciiFalse, indent2) print(f✅ 参数组合测试完成: {param_desc}) else: print(f❌ 参数组合测试失败: {param_desc}) except Exception as e: print(f❌ 测试参数组合时出错: {e}) continue # 延迟避免服务器过载 time.sleep(2) # 生成测试报告 self.generate_test_report(results, test_output_dir) return results def generate_test_report(self, results: Dict[str, Dict], output_dir: str): 生成参数测试报告 report_path os.path.join(output_dir, test_report.md) with open(report_path, w, encodingutf-8) as f: f.write(# 参数测试报告\n\n) f.write(f生成时间: {datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n) f.write(f测试组合总数: {len(results)}\n\n) f.write(## 测试结果汇总\n\n) f.write(| 序号 | 参数组合 | 图片文件 | 状态 |\n) f.write(|------|----------|----------|------|\n) for i, (param_desc, result) in enumerate(results.items(), 1): filename os.path.basename(result[filepath]) f.write(f| {i} | {param_desc} | {filename} | ✅ 成功 |\n) f.write(\n## 详细参数配置\n\n) for param_desc, result in results.items(): f.write(f### {param_desc}\n\n) f.write(f- **图片文件**: {os.path.basename(result[filepath])}\n) f.write(f- **提示词**: {result[prompt]}\n) f.write(- **参数**:\n) for param_name, param_value in result[parameters].items(): f.write(f - {param_name}: {param_value}\n) f.write(\n) print(f 测试报告已生成: {report_path}) # 使用示例 def parameter_grid_test(): 参数网格测试示例 generator AdvancedBatchGenerator() # 定义参数网格 parameter_grid { steps: [20, 25, 30], # 测试不同推理步数 cfg_scale: [7.0, 8.0, 9.0], # 测试不同CFG值 # 可以添加更多参数 } base_prompt A beautiful landscape with mountains and lakes, ultra HD, realistic results generator.generate_with_parameter_grid( workflow_pathflux_workflow.json, base_promptbase_prompt, parameter_gridparameter_grid, output_dirparameter_tests ) print(f\n 参数测试完成共测试{len(results)}种组合)4.2 从文件读取提示词对于大规模的批量生成从文件读取提示词更加方便class FileBasedBatchGenerator(ComfyUIBatchGenerator): 基于文件的批量生成器 def load_prompts_from_file(self, filepath: str, format_type: str txt) - List[str]: 从文件加载提示词列表 Args: filepath: 文件路径 format_type: 文件格式支持 txt, csv, json Returns: 提示词列表 prompts [] try: if format_type txt: # 从文本文件读取每行一个提示词 with open(filepath, r, encodingutf-8) as f: for line in f: line line.strip() if line and not line.startswith(#): # 跳过空行和注释 prompts.append(line) elif format_type csv: # 从CSV文件读取 import csv with open(filepath, r, encodingutf-8) as f: reader csv.reader(f) for row in reader: if row and row[0].strip(): prompts.append(row[0].strip()) elif format_type json: # 从JSON文件读取 with open(filepath, r, encodingutf-8) as f: data json.load(f) if isinstance(data, list): prompts data elif isinstance(data, dict) and prompts in data: prompts data[prompts] print(f✅ 从文件加载了{len(prompts)}个提示词: {filepath}) return prompts except Exception as e: print(f❌ 加载提示词文件失败: {e}) return [] def batch_generate_from_file(self, workflow_path: str, prompts_file: str, file_format: str txt, output_dir: str batch_from_file, **kwargs) - List[str]: 从文件批量生成图片 Args: workflow_path: 工作流文件路径 prompts_file: 提示词文件路径 file_format: 文件格式 output_dir: 输出目录 **kwargs: 其他参数传递给batch_generate Returns: 生成的图片路径列表 # 从文件加载提示词 prompts self.load_prompts_from_file(prompts_file, file_format) if not prompts: print(❌ 未加载到有效提示词批量生成终止) return [] # 调用批量生成 return self.batch_generate( workflow_pathworkflow_path, promptsprompts, output_diroutput_dir, **kwargs ) # 使用示例 def file_based_generation(): 基于文件的批量生成示例 # 首先创建一个提示词文件 prompts_content # 商品描述提示词列表 A modern minimalist chair design, white background, product photography, 8K A luxury watch on black velvet, studio lighting, detailed macro shot A smartphone showing app interface, floating in space, concept art A pair of running shoes on mountain trail, action shot, dynamic lighting A ceramic coffee mug with steam rising, morning sunlight, cozy atmosphere A leather wallet with credit cards, flat lay composition, professional A gaming laptop with RGB lighting, futuristic design, cyberpunk style A bouquet of fresh flowers in glass vase, soft focus, romantic mood A set of kitchen knives on wooden cutting board, chefs tools, sharp A camping tent under starry night, long exposure, adventure photography # 保存到文件 with open(product_prompts.txt, w, encodingutf-8) as f: f.write(prompts_content) print( 提示词文件已创建: product_prompts.txt) # 从文件批量生成 generator FileBasedBatchGenerator() generated_files generator.batch_generate_from_file( workflow_pathflux_workflow.json, prompts_fileproduct_prompts.txt, file_formattxt, output_dirproduct_images, batch_prefixproduct_batch, steps25, width1024, height1024 ) print(f\n️ 商品图片批量生成完成共生成{len(generated_files)}张图片)5. 实战应用与优化建议掌握了批量生成脚本的基本用法后我们来看看如何在实际项目中应用和优化。5.1 电商内容生成实战假设你是一个电商运营需要为100个商品生成营销图片。我们可以这样优化脚本def ecommerce_batch_generation(): 电商内容批量生成优化版 generator ComfyUIBatchGenerator() # 电商商品提示词模板 product_templates [ Professional product photo of {product}, white background, studio lighting, 8K resolution, detailed, {product} in natural environment, lifestyle photography, authentic, realistic lighting, Close-up shot of {product}, showing texture and details, macro photography, sharp focus, {product} with creative composition, artistic style, unique perspective, visually striking, {product} in use scenario, showing functionality, practical photography, relatable ] # 商品列表 products [ wireless Bluetooth headphones, smart fitness watch, portable power bank, ergonomic office chair, stainless steel water bottle, wireless charging pad, noise cancelling earbuds, gaming mechanical keyboard, 4K action camera, smart home speaker ] all_prompts [] # 为每个商品生成多种风格的提示词 for product in products: for template in product_templates: prompt template.format(productproduct) all_prompts.append(prompt) print(f 为{len(products)}个商品生成{len(all_prompts)}张图片) # 分批处理避免一次性提交太多任务 batch_size 5 all_generated_files [] for i in range(0, len(all_prompts), batch_size): batch_prompts all_prompts[i:i batch_size] batch_num i // batch_size 1 print(f\n 处理第{batch_num}批共{len(batch_prompts)}个提示词) generated_files generator.batch_generate( workflow_pathflux_workflow.json, promptsbatch_prompts, output_dirfecommerce_batch_{batch_num:03d}, batch_prefixfproduct_batch_{batch_num}, steps25, width1024, height1024 ) all_generated_files.extend(generated_files) # 批次间休息避免服务器压力 if i batch_size len(all_prompts): print(f⏸️ 批次完成等待10秒继续...) time.sleep(10) # 生成电商专用的元数据 generate_ecommerce_metadata(all_generated_files, products) print(f\n 电商批量生成完成共生成{len(all_generated_files)}张商品图片) def generate_ecommerce_metadata(image_files: List[str], products: List[str]): 生成电商图片元数据 metadata { generation_date: datetime.now().isoformat(), total_images: len(image_files), products: products, images: [] } for i, filepath in enumerate(image_files): filename os.path.basename(filepath) product_index i // 5 # 假设每个商品5种风格 if product_index len(products): product products[product_index] style_index i % 5 styles [studio, lifestyle, detail, creative, usage] style styles[style_index] if style_index len(styles) else unknown image_info { filename: filename, filepath: filepath, product: product, style: style, suggested_use: get_suggested_use(style) } metadata[images].append(image_info) # 保存元数据 metadata_file ecommerce_metadata.json with open(metadata_file, w, encodingutf-8) as f: json.dump(metadata, f, ensure_asciiFalse, indent2) print(f 电商元数据已保存: {metadata_file}) def get_suggested_use(style: str) - str: 根据图片风格建议使用场景 suggestions { studio: 产品主图、详情页首图, lifestyle: 场景展示、社交媒体, detail: 细节展示、材质特写, creative: 广告创意、品牌宣传, usage: 功能演示、使用教程 } return suggestions.get(style, 通用展示)5.2 性能优化建议当处理大量生成任务时性能优化很重要class OptimizedBatchGenerator(ComfyUIBatchGenerator): 优化版批量生成器 def __init__(self, server_address: str http://localhost:8188, max_concurrent: int 2): 初始化优化生成器 Args: server_address: 服务器地址 max_concurrent: 最大并发数 super().__init__(server_address) self.max_concurrent max_concurrent self.active_tasks [] def optimized_batch_generate(self, workflow_path: str, prompts: List[str], output_dir: str optimized_output, **kwargs) - List[str]: 优化版批量生成支持并发控制 Args: workflow_path: 工作流文件路径 prompts: 提示词列表 output_dir: 输出目录 **kwargs: 其他参数 Returns: 生成的图片路径列表 import threading from queue import Queue print(f⚡ 使用优化批量生成最大并发: {self.max_concurrent}) # 加载工作流 base_workflow self.load_workflow(workflow_path) if not base_workflow: return [] # 创建输出目录 batch_time datetime.now().strftime(%Y%m%d_%H%M%S) batch_output_dir os.path.join(output_dir, fbatch_{batch_time}) os.makedirs(batch_output_dir, exist_okTrue) # 使用队列管理任务 task_queue Queue() result_queue Queue() # 添加所有任务到队列 for i, prompt in enumerate(prompts): task_queue.put((i, prompt)) # 工作线程函数 def worker(): while not task_queue.empty(): try: i, prompt task_queue.get_nowait() print(f 工作线程处理任务 {i1}/{len(prompts)}) try: filepath self.generate_single_image( workflowbase_workflow, prompt_textprompt, output_dirbatch_output_dir, image_prefixfimg_{i1:03d}, **{k: v for k, v in kwargs.items() if k in [steps, width, height]} ) if filepath: result_queue.put((i, filepath, True)) else: result_queue.put((i, None, False)) except Exception as e: print(f❌ 任务 {i1} 执行出错: {e}) result_queue.put((i, None, False)) task_queue.task_done() except: break # 启动工作线程 threads [] for _ in range(min(self.max_concurrent, len(prompts))): thread threading.Thread(targetworker) thread.start() threads.append(thread) # 等待所有任务完成 for thread in threads: thread.join() # 收集结果 results [None] * len(prompts) success_count 0 while not result_queue.empty(): i, filepath, success result_queue.get() results[i] filepath if success: success_count 1 # 过滤成功的结果 generated_files [f for f in results if f] print(f\n 优化批量生成完成:) print(f 成功: {success_count}/{len(prompts)}) print(f 失败: {len(prompts) - success_count}) print(f 输出目录: {batch_output_dir}) return generated_files # 使用优化版生成器 def optimized_generation_example(): 优化批量生成示例 # 生成大量提示词 base_prompts [ A beautiful {scene} at {time}, {style} style, {quality}, An artistic depiction of {subject}, {mood} atmosphere, {style}, A detailed illustration of {concept}, {perspective} view, {details} ] scenes [mountain landscape, ocean view, forest path, city skyline] times [sunrise, noon, sunset, night] styles [realistic, digital art, painting, sketch] qualities [8K resolution, high detail, professional photography, cinematic] all_prompts [] # 生成组合提示词 for scene in scenes: for time in times: for style in styles: for quality in qualities: prompt fA beautiful {scene} at {time}, {style} style, {quality} all_prompts.append(prompt) print(f 生成{len(all_prompts)}个组合提示词) # 使用优化生成器 generator OptimizedBatchGenerator(max_concurrent3) # 只测试前20个避免生成太多 test_prompts all_prompts[:20] generated_files generator.optimized_batch_generate( workflow_pathflux_workflow.json, promptstest_prompts, output_diroptimized_batch, steps20, width768, height768 ) print(f\n✅ 优化批量生成测试完成生成{len(generated_files)}张图片)6. 总结与最佳实践通过本文的讲解你已经掌握了使用ComfyUI API编写批量生成脚本的核心技能。让我们回顾一下关键要点6.1 核心收获API接口掌握学会了如何通过HTTP API与ComfyUI交互这是批量自动化的基础工作流操作掌握了加载、修改工作流配置的方法能够动态调整生成参数批量生成实现构建了完整的批量生成流程从提示词处理到结果保存高级功能扩展实现了参数测试、文件读取、并发优化等实用功能实战应用了解了如何在实际项目中应用这些技术6.2 最佳实践建议根据我的实践经验这里有一些建议可以帮助你更好地使用批量生成脚本提示词管理技巧使用模板系统避免重复编写相似提示词建立提示词库分类管理不同场景的提示词使用变量替换实现动态提示词生成性能优化建议控制并发数量避免服务器过载分批处理大量任务每批完成后适当休息监控显存使用及时清理缓存错误处理策略添加重试机制处理网络波动记录详细日志方便问题排查实现断点续传避免任务中断结果管理方案使用有意义的文件名方便后续查找保存生成参数和提示词到元数据文件定期整理和备份生成结果6.3 下一步学习方向掌握了基础批量生成后你可以进一步探索工作流自动化结合其他工具实现端到端的自动化流程质量评估添加自动评分系统筛选高质量图片风格迁移批量应用LoRA模型统一图片风格云端部署将脚本部署到云服务器实现24小时不间断生成Web界面为脚本添加Web界面方便非技术人员使用批量生成脚本的真正价值在于解放你的创造力。你不必再被重复操作束缚可以专注于提示词的优化、风格的探索、创意的实现。技术应该服务于创作而不是成为创作的障碍。希望这个脚本能成为你创作路上的得力助手。如果你在实践过程中遇到任何问题或者有更好的改进建议欢迎交流分享。记住最好的脚本是那个最适合你工作流程的脚本不要害怕根据自己的需求进行修改和优化。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

相关文章:

openclaw技术实践:Nunchaku FLUX.1-dev ComfyUI批量生成脚本编写

openclaw技术实践:Nunchaku FLUX.1-dev ComfyUI批量生成脚本编写 你是不是也遇到过这样的场景?在ComfyUI里用Nunchaku FLUX.1-dev模型生成了一张惊艳的图片,然后想:“要是能批量生成不同风格、不同主题的图片就好了。”但每次都要…...

【图像增强】基于matlab HSI和局部同态滤波的彩色图像增强【含Matlab源码 15314期】

💥💥💥💥💥💥💞💞💞💞💞💞💞💞欢迎来到海神之光博客之家💞💞💞&#x1f49…...

【水声通信】基于matlab UWOC与OIRS协同通过减轻湍流和优化性能增强水下通信【含Matlab源码 15313期】

💥💥💥💥💥💥💞💞💞💞💞💞💞💞欢迎来到海神之光博客之家💞💞💞&#x1f49…...

OpCore-Simplify终极指南:如何10分钟完成黑苹果EFI配置

OpCore-Simplify终极指南:如何10分钟完成黑苹果EFI配置 【免费下载链接】OpCore-Simplify A tool designed to simplify the creation of OpenCore EFI 项目地址: https://gitcode.com/GitHub_Trending/op/OpCore-Simplify 还在为复杂的OpenCore配置而头痛吗…...

D3KeyHelper:5分钟告别暗黑3重复操作,智能按键宏解放你的双手

D3KeyHelper:5分钟告别暗黑3重复操作,智能按键宏解放你的双手 【免费下载链接】D3keyHelper D3KeyHelper是一个有图形界面,可自定义配置的暗黑3鼠标宏工具。 项目地址: https://gitcode.com/gh_mirrors/d3/D3keyHelper 还在为暗黑破坏…...

高阶 Rust:20% 代价换 80% 收益的编程新路径

【导语:在寻找完美编程语言的过程中,Rust 虽优点突出但开发效率低。如今提出高阶 Rust 方法,用 20% 代价获 80% 好处,为编程领域带来新思考。】传统编程语言的困境与 Rust 的潜力多年来,开发者一直在寻找完美的编程语言…...

Graphormer分子图建模原理:原子中心编码与键距离注意力机制详解

Graphormer分子图建模原理:原子中心编码与键距离注意力机制详解 1. Graphormer模型概述 Graphormer是微软研究院开发的一种基于纯Transformer架构的图神经网络模型,专门为分子图(原子-键结构)的全局结构建模与属性预测而设计。该…...

Source Han Serif CN:免费开源宋体的7种字重完整使用教程

Source Han Serif CN:免费开源宋体的7种字重完整使用教程 【免费下载链接】source-han-serif-ttf Source Han Serif TTF 项目地址: https://gitcode.com/gh_mirrors/so/source-han-serif-ttf 还在为商业项目寻找高质量中文字体而烦恼吗?Source Ha…...

每月 20 美元技术栈:低成本运营高收益软件公司的秘诀

【导语:在科技行业普遍追求高额融资与复杂架构的当下,Steve Hanov 分享了用每月 20 美元技术栈运营多家月经常性收入达 1 万美元公司的经验,为低成本创业提供了新思路。】精简服务器:告别 AWS 高成本2026 年,启动 AWS …...

UE5特效与逻辑分离实战:用Niagara做炫酷弹道,用蓝图处理伤害判定(避坑指南)

UE5特效与逻辑分离实战:用Niagara做炫酷弹道,用蓝图处理伤害判定(避坑指南) 在UE5游戏开发中,弹道效果的处理往往面临一个核心矛盾:既要追求视觉上的华丽表现,又要确保游戏逻辑的精确性。传统做…...

如何快速上手p5.js Web Editor:免费在线创意编程的终极指南

如何快速上手p5.js Web Editor:免费在线创意编程的终极指南 【免费下载链接】p5.js-web-editor The p5.js Editor is a website for creating p5.js sketches, with a focus on making coding accessible and inclusive for artists, designers, educators, beginne…...

从理论到实践:解析上下文无关文法与下推自动机的等价性及其应用

1. 上下文无关文法:编程语言的骨架 第一次接触上下文无关文法(CFG)时,我正尝试为团队设计一个简单的领域专用语言(DSL)。当时完全没想到,这个看似抽象的理论概念,竟成了解决实际问题的金钥匙。简单来说,上下文无关文法…...

3个技巧让SonarQube代码质量报告变得专业易读

3个技巧让SonarQube代码质量报告变得专业易读 【免费下载链接】sonar-cnes-report Generates analysis reports from SonarQube web API. 项目地址: https://gitcode.com/gh_mirrors/so/sonar-cnes-report 你是否曾在面对SonarQube密密麻麻的质量指标时感到无从下手&…...

不用VGG16也能行?在乳腺超声分类任务上快速对比ResNet50与MobileNetV3

医学图像分类实战:ResNet50与MobileNetV3在乳腺超声诊断中的横向评测 当医疗AI遇上轻量化模型,我们该如何在精度与效率之间寻找平衡点?乳腺超声图像的自动分类一直是计算机辅助诊断系统的核心挑战。传统VGG16架构虽然表现稳定,但…...

Lattice Diamond IP核配置实战:从新建项目到生成BIT文件的完整流程

Lattice Diamond IP核配置实战:从新建项目到生成BIT文件的完整流程 在FPGA开发领域,Lattice Diamond以其轻量级和高效性赢得了不少开发者的青睐。不同于Xilinx和Altera(现Intel)的庞大工具链,Diamond提供了更简洁的工作…...

一个人生倒计时的网页应用

这是一个非常棒的想法!开发一个“人生倒计时”网页应用不仅能帮助用户直观地感受时间,也是学习 HTML、CSS 和 JavaScript 协同工作的经典实践。为了确保我提供的代码完全符合你的需求,我先确认一下初步的功能设想:1. 核心逻辑概述…...

SAP自定义打印机纸张类型:从SPAD到SmartForm的完整指南

1. SAP自定义打印机纸张类型的必要性 第一次接触SAP打印功能时,我也以为系统自带的A3、A4标准纸张就能满足所有需求。直到遇到客户要求打印特殊尺寸的送货单,才发现现实场景远比想象复杂。比如物流行业常用的三联单、仓库的条形码标签、财务的特殊凭证&a…...

Python AI爬虫实战:爬取张雪峰微博并进行情感分析与词云可视化剖

1. 引入 在现代 AI 工程中,Hugging Face 的 tokenizers 库已成为分词器的事实标准。不过 Hugging Face 的 tokenizers 是用 Rust 来实现的,官方只提供了 python 和 node 的绑定实现。要实现与 Hugging Face tokenizers 相同的行为,最好的办法…...

ArcGIS实战:如何将不同分辨率DEM进行无缝镶嵌以扩展地形分析范围

1. 为什么需要融合不同分辨率的DEM数据 第一次用高精度DEM做地形分析时,我就被坑惨了。当时手头有份2米分辨率的激光雷达数据,精度高到能看清每条田间小路。但当我把它加载到全局地图时,发现四周全是空白——就像把高清照片贴在白墙上那么突兀…...

ConvNeXt 系列改进:ConvNeXt 与 Swin Transformer 融合:构建 CSWin 混合 Block,超越纯 CNN

摘要:在 2026 年的计算机视觉(CV)主干网络发展中,纯卷积神经网络(CNN)与纯视觉 Transformer(ViT)的“路线之争”已落下帷幕,“混合架构(Hybrid Architecture)”全面接管了 SOTA 榜单。根据 2026 年 3 月最新发表的多篇顶会与医学视觉核心论文(如 CS-Net、HyCoSwin …...

OpenClaw入门案例:第一个龙虾智能体程序(Hello World版,复制可运行)

OpenClaw入门案例:第一个龙虾智能体程序(Hello World版,复制可运行)📚 本章学习目标:深入理解OpenClaw入门案例的核心概念与实践方法,掌握关键技术要点,了解实际应用场景与最佳实践。…...

从零实现富文本编辑器#-React可编辑节点的组件预设泄

1. 智能软件工程的范式转移:从库集成到原生框架演进 在生成式人工智能(Generative AI)从单纯的文本生成向具备自主规划与执行能力的“代理化(Agentic)”系统跨越的过程中,.NET 生态系统正在经历一场自该平台…...

UniversalSplitScreen:让任何游戏都能分屏游玩的终极解决方案

UniversalSplitScreen:让任何游戏都能分屏游玩的终极解决方案 【免费下载链接】UniversalSplitScreen Split screen multiplayer for any game with multiple keyboards, mice and controllers. 项目地址: https://gitcode.com/gh_mirrors/un/UniversalSplitScree…...

Java实战:从零构建一个支持微积分运算的科学计算器

1. 科学计算器的核心功能设计 构建一个支持微积分运算的科学计算器,首先要明确功能边界。基础功能包括四则运算、三角函数、指数对数等常规计算,而核心难点在于微积分功能的实现。我建议采用模块化设计思路,将计算器分为三个层次:…...

FPGA 实现 YCbCr 到 RGB 色彩空间转换的定点化设计

1. 色彩空间转换的基础原理 第一次接触YCbCr和RGB转换时,我完全被那些小数系数搞晕了。后来才发现,这其实就是把颜色信息用不同方式"打包"的过程。想象你有一套乐高积木,RGB是按红绿蓝三种基础积木的数量来记录,而YCbCr…...

RK3562J与MCP2518FD通信测试全记录:从双板互发数据到常见错误分析

RK3562J与MCP2518FD通信实战:从双板互发到异常诊断全解析 当两块开发板通过CAN-FD总线成功交换数据的瞬间,那种"灯亮起来"的成就感是嵌入式开发者独有的快乐。RK3562J作为瑞芯微新一代工业级处理器,其与MCP2518FD的组合在车载诊断、…...

ESP32 IDF环境下LVGL显示GIF的避坑指南:内存配置与性能优化

ESP32 IDF环境下LVGL显示GIF的避坑指南:内存配置与性能优化 在嵌入式设备上实现流畅的GIF动画显示一直是开发者面临的挑战,尤其是资源受限的ESP32平台。本文将深入探讨ESP32 IDF环境下使用LVGL显示GIF时可能遇到的内存和性能问题,并提供一系列…...

Geo-SAM技术解析:基于QGIS的地理空间AI图像分割架构与实现

Geo-SAM技术解析:基于QGIS的地理空间AI图像分割架构与实现 【免费下载链接】Geo-SAM A QGIS plugin tool using Segment Anything Model (SAM) to accelerate segmenting or delineating landforms in geospatial raster images. 项目地址: https://gitcode.com/g…...

201-基于Wasserstein的分布式鲁棒优化:精确刻画风电出力概率分布与混合整数线性规划...

201-基于Wasserstein的分布式鲁棒优化 研究内容:结合Wasserstein距离实现风电出力概率分布模糊集的精确刻画,并运用线性决策规则与强对偶理论将其转换为混合整数线性规划模型求解 注意事项:并没有对全文进行复现,通过算例&#xf…...

2025最权威的五大AI论文平台推荐榜单

Ai论文网站排名(开题报告、文献综述、降aigc率、降重综合对比) TOP1. 千笔AI TOP2. aipasspaper TOP3. 清北论文 TOP4. 豆包 TOP5. kimi TOP6. deepseek 借助人工智能来辅助撰写开题报告,这是需要依照系统性方法去做的。首先呢&#xf…...