-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path05_advanced_features.py
More file actions
195 lines (142 loc) · 5.49 KB
/
05_advanced_features.py
File metadata and controls
195 lines (142 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""
Advanced Features Example - Batch Execution, Error Handling, and More
Learn advanced ComfyKit features for production use.
"""
import asyncio
from pathlib import Path
from comfykit import ComfyKit
async def example_batch_execution():
"""Example 1: Execute multiple workflows"""
print("\n=== Example 1: Batch Execution ===")
kit = ComfyKit()
prompts = [
"a cat",
"a dog",
"a bird"
]
print(f"Executing {len(prompts)} workflows...")
tasks = [
kit.execute(
"workflows/t2i_by_local_flux.json",
{"prompt": prompt}
)
for prompt in prompts
]
results = await asyncio.gather(*tasks, return_exceptions=True)
success = sum(1 for r in results if not isinstance(r, Exception))
print(f"✓ Completed: {success}/{len(prompts)}")
# Verify
assert success > 0, "At least one should succeed"
async def example_error_handling():
"""Example 2: Handle execution errors"""
print("\n=== Example 2: Error Handling ===")
kit = ComfyKit()
try:
result = await kit.execute(
"non_existent_workflow.json",
{"prompt": "test"}
)
if result.status == "error":
print(f"✓ Handled error: {result.msg}")
else:
print(f"✓ Success: {result.status}")
except FileNotFoundError as e:
print(f"✓ Caught expected error: {e}")
except Exception as e:
print(f"✓ Caught error: {type(e).__name__}")
async def example_timeout_handling():
"""Example 3: Handle timeouts"""
print("\n=== Example 3: Timeout Handling ===")
kit = ComfyKit(runninghub_timeout=10) # 10 seconds
print(f"✓ Timeout set to {kit.runninghub_timeout}s")
print("✓ Long-running tasks will timeout gracefully")
async def example_auth_configuration():
"""Example 4: Authentication"""
print("\n=== Example 4: Authentication ===")
# With API key
kit = ComfyKit(
api_key="your-api-key",
cookies="session=abc123"
)
print(f"✓ API key: {'***' if kit.api_key else 'None'}")
print(f"✓ Cookies: {'***' if kit.cookies else 'None'}")
print("✓ Authentication configured")
async def example_executor_types():
"""Example 5: Different executor types"""
print("\n=== Example 5: Executor Types ===")
# HTTP (default, recommended)
http_kit = ComfyKit(executor_type="http")
print(f"✓ HTTP mode: {http_kit.executor_type}")
# WebSocket (for long-running tasks)
ws_kit = ComfyKit(executor_type="websocket")
print(f"✓ WebSocket mode: {ws_kit.executor_type}")
# Verify
assert http_kit.executor_type == "http"
assert ws_kit.executor_type == "websocket"
async def example_result_processing():
"""Example 6: Process results"""
print("\n=== Example 6: Result Processing ===")
kit = ComfyKit()
result = await kit.execute(
"workflows/t2i_by_local_flux.json",
{"prompt": "a test image"}
)
# Different ways to access results
print(f"✓ Status: {result.status}")
print(f"✓ Duration: {result.duration}s")
print(f"✓ Prompt ID: {result.prompt_id}")
# All images (flat list)
print(f"✓ Total images: {len(result.images)}")
# Images by variable name
for var_name, images in result.images_by_var.items():
print(f"✓ Variable '{var_name}': {len(images)} images")
# Check different output types
if result.videos:
print(f"✓ Videos: {len(result.videos)}")
if result.audios:
print(f"✓ Audios: {len(result.audios)}")
if result.texts:
print(f"✓ Texts: {len(result.texts)}")
async def example_workflow_from_path():
"""Example 7: Different workflow sources"""
print("\n=== Example 7: Workflow Sources ===")
kit = ComfyKit()
# From string path
result1 = await kit.execute("workflows/t2i_by_local_flux.json")
print(f"✓ From string path: {result1.status}")
# From Path object
result2 = await kit.execute(
Path("workflows/t2i_by_local_flux.json")
)
print(f"✓ From Path object: {result2.status}")
# From URL (downloads automatically)
# result3 = await kit.execute("https://example.com/workflow.json")
# print(f"✓ From URL: {result3.status}")
# From RunningHub ID
# result4 = await kit.execute("12345")
# print(f"✓ From RunningHub ID: {result4.status}")
async def main():
print("🚀 ComfyKit Advanced Features Examples")
print("="*60)
print("\n💡 These examples show production-ready features\n")
try:
await example_batch_execution()
await example_error_handling()
await example_timeout_handling()
await example_auth_configuration()
await example_executor_types()
await example_result_processing()
await example_workflow_from_path()
print("\n" + "="*60)
print("✨ All advanced examples completed!")
print("\n📝 Key Takeaways:")
print(" 1. Batch execution with asyncio.gather()")
print(" 2. Graceful error handling")
print(" 3. Flexible authentication options")
print(" 4. Multiple executor types available")
print(" 5. Rich result processing")
except Exception as e:
print(f"\n❌ Error: {e}")
print("\n💡 Some examples require a running ComfyUI server")
if __name__ == "__main__":
asyncio.run(main())