async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_Executing_Prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_Executing_Prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
except ValueError as e:
print("Incompatible response from ComfyUI");
history = self.get_history(prompt_id)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
for item in node_output:
match item:
case "text":
outputs.append(node_output['text'][0])
break
case "audio":
outputs[node_id] = self.get_audio(item)
break
case "music":
outputs[node_id] = self.get_music(item)
break
case "images":
outputs[node_id] = self.get_image(item['filename'], item['subfolder'], item['type'])
break
case "images":
for image in node_output['images']:
image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
if 'final_output' in image['filename']:
pil_image = Image.open(BytesIO(image_data))
outputs.append(pil_image)
break
case _:
continue
return outputs
如果您希望在每个 case 分支运行后都返回结果,您可以简单地在每个匹配分支的末尾添加一个 return 语句。下面是更新后的代码:
User
async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_Executing_Prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_Executing_Prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
except ValueError as e:
print("Incompatible response from ComfyUI");
history = self.get_history(prompt_id)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
for item in node_output:
match item:
case "text":
outputs.append(node_output['text'][0])
return outputs
case "audio":
outputs[node_id] = self.get_audio(item)
return outputs
case "music":
outputs[node_id] = self.get_music(item)
return outputs
case "images":
outputs[node_id] = self.get_image(item['filename'], item['subfolder'], item['type'])
return outputs
case "images":
for image in node_output['images']:
image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
if 'final_output' in image['filename']:
pil_image = Image.open(BytesIO(image_data))
outputs.append(pil_image)
return outputs
case _:
continue
return []
# ...
prompt_id = self.queue_prompt(prompt)['prompt_id']
print(f"Queued prompt with ID: {prompt_id}") # Debugging print
# ...
history = self.get_history(prompt_id)
print(f"History obtained for prompt ID {prompt_id}: {history}") # Debugging print
# Ensure the prompt_id key exists
if prompt_id not in history:
print(f"Error: No history found for prompt ID {prompt_id}")
return [] # Or handle the error as appropriate
# Now we securely access the history for the given prompt_id
# If this raises a KeyError, it's because prompt_id wasn't returned by get_history as expected
prompt_history = history[prompt_id]
User
async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_Executing_Prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_Executing_Prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
except ValueError as e:
print("Incompatible response from ComfyUI");
history = self.get_history(prompt_id)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
for item in node_output:
match item:
case "text":
outputs.append(node_output['text'][0])
return outputs
case "audio":
outputs[node_id] = self.get_audio(item)
return outputs
case "music":
outputs[node_id] = self.get_music(item)
return outputs
case "images":
outputs[node_id] = self.get_image(item['filename'], item['subfolder'], item['type'])
return outputs
case "images":
for image in node_output['images']:
image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
if 'final_output' in image['filename']:
pil_image = Image.open(BytesIO(image_data))
outputs.append(pil_image)
return outputs
case _:
continue
return []
get_history 好像根本没有等待 comfyui 运行完毕,导致 history = self.get_history(prompt_id)[prompt_id] 出现问题?
E 2024-02-29 16:18:29,013 hikari.event_manager: an exception occurred handling an event (InteractionCreateEvent)
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/websockets/legacy/protocol.py", line 974, in transfer_data
await asyncio.shield(self._put_message_waiter)
asyncio.exceptions.CancelledError
Assistant
The error message you're seeing indicates that an exception (CancelledError) occurred during the handling of a WebSocket event – specifically, while waiting for a message to be sent or received over the WebSocket connection. CancelledError is a subclass of Exception, which is raised when an asyncio Task or Future is cancelled.
async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_Executing_Prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_Executing_Prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
except ValueError as e:
print("Incompatible response from ComfyUI");
# Retrieve the history outside of the async for loop
# This way, you prevent retrieving the history multiple times unnecessarily
break
history = self.get_history(prompt_id)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
for item in node_output:
match item:
case "text":
outputs.append(node_output['text'][0])
# Return right after the append operation
return outputs
case "audio":
outputs[node_id] = self.get_audio(item)
case "music":
outputs[node_id] = self.get_music(item)
case "images":
for image in node_output['images']:
image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
if 'final_output' in image['filename']:
pil_image = Image.open(BytesIO(image_data))
outputs.append(pil_image)
# Return right after processing the images
return outputs
case _:
continue
return outputs
我发现代码可能包含一些逻辑错误(例如,同样的 case "images" 出现了两次,并且在循环中不应使用 outputs[node_id] 赋值,因为 outputs 被初始化为一个列表,应该使用 append())。上面的修改将修改后对这些问题进行了一定程度的修正,但如果输出历史有不同类型的输出,并且您希望收集所有类型的输出,您可能不希望在添加文本输出后立即返回。
如果代码有特定的预期行为,请确保相应地修改逻辑以满足您的需求。
async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_executing_prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_executing_prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
except ValueError as e:
print("Incompatible response from ComfyUI")
# Retrieve the history outside of the async for loop
history = self.get_history(prompt_id)[prompt_id]
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
for item in node_output:
match item:
case "text":
outputs.append(node_output['text'][0])
return outputs # Return after text case
case "audio":
outputs.append(self.get_audio(node_output['audio']))
return outputs # Return after audio case
case "music":
outputs.append(self.get_music(node_output['music']))
return outputs # Return after music case
case "images":
for image in node_output['images']:
image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
if 'final_output' in image['filename']:
pil_image = Image.open(BytesIO(image_data))
outputs.append(pil_image)
return outputs # Return after images case
case _:
continue # Skip unknown items
# If the loop completes without returning, just return the outputs collected so far
return outputs
为确保在调用 get_history 前 prompt_id 的执行完全结束,您应只在 async for 循环结束后调用该方法。让我们修复这段代码,使其在收到所有执行输出后才调用 get_history。请参考以下修订后的代码:
async def get_output(self, prompt):
if not self.ws:
await self.connect()
prompt_id = self.queue_prompt(prompt)['prompt_id']
outputs = []
currently_Executing_Prompt = None
async for out in self.ws:
try:
message = json.loads(out)
if message['type'] == 'execution_start':
currently_Executing_Prompt = message['data']['prompt_id']
if message['type'] == 'executing' and prompt_id == currently_Executing_Prompt:
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break # Exit loop when execution for prompt_id is complete
except ValueError as e:
print("Incompatible response from ComfyUI")
# Now that execution has ended, retrieve history outside the async for loop
history = self.get_history(prompt_id)
# Ensure the prompt_id key exists in history
if prompt_id not in history:
print(f"No history found for prompt ID {prompt_id}")
return [] # Handle the missing history case
prompt_history = history[prompt_id] # Safely retrieve history using the prompt_id
# Continue processing outputs assuming we have valid prompt_history
for node_id in prompt_history['outputs']:
node_output = prompt_history['outputs'][node_id]
for output_type, output_content in node_output.items():
match output_type:
case "text":
outputs.append(output_content[0])
return outputs
# And so on for other cases...
case _:
continue
return outputs
This error often occurs when your async coroutine is cancelled while it's waiting for an operation to complete. In websockets and asyncio, cancellation is a way to stop an ongoing operation that is no longer needed or is taking too long.
Here are a few possible reasons for this to happen:
Explicit Cancellation: There might be some explicit cancellation happening within your code, where you're cancelling tasks manually.
Timeout Management: You might have some timeout code that, when a certain amount of time passes, cancels all tasks.
Shutdown Procedure: During shutdown or restart of your application, ongoing tasks might be cancelled to allow for a clean close of all connections.
Exception Handling: An exception occurred elsewhere which led to the task where this WebSocket event was being handled getting cancelled.
To handle this scenario, you may need to look at the broader context in which this error is occurring:
Review the code to see if there's a task cancellation mechanism in place that might be prematurely cancelling your WebSocket tasks.
Ensure that you have proper exception handling to catch and handle CancelledError where you await on other coroutines, to cleanly exit or to take a specific action.
If your application is shutting down or restarting, ensure that you have a graceful shutdown procedure that waits for tasks to complete or reaches a safe point before cancellation.
Without seeing the full code and understanding the context, it's challenging to provide a specific solution. However, often these errors require improving the resilience of your asynchronous task handling and ensuring that tasks are not being left incomplete during event handling.
If you need further assistance, please provide more context or code snippets where this error occurs so we can offer more targeted advice.