-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
325 lines (265 loc) Β· 9.78 KB
/
handler.py
File metadata and controls
325 lines (265 loc) Β· 9.78 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
"""
RunPod Serverless Handler for ComfyUI with Wan Animate
Enhanced with model management, better error handling, and optimization
"""
import runpod
import json
import os
import sys
import uuid
import base64
import shutil
import time
from pathlib import Path
from io import BytesIO
# Add ComfyUI to path
sys.path.insert(0, '/comfyui')
# Global variables for optimization
COMFYUI_SERVER = None
EXECUTION_COUNT = 0
MAX_EXECUTIONS_PER_INSTANCE = 100 # Restart after this many executions
def setup_directories():
"""Ensure all required directories exist"""
directories = [
'/comfyui/input',
'/comfyui/output',
'/comfyui/temp'
]
for directory in directories:
Path(directory).mkdir(parents=True, exist_ok=True)
def clear_directories():
"""Clear temporary directories to free up space"""
try:
# Clear temp directory
temp_dir = Path('/comfyui/temp')
if temp_dir.exists():
shutil.rmtree(temp_dir)
temp_dir.mkdir(exist_ok=True)
# Clear input directory (keep recent files)
input_dir = Path('/comfyui/input')
if input_dir.exists():
for file in input_dir.glob('*'):
if file.stat().st_mtime < time.time() - 3600: # Older than 1 hour
file.unlink()
print("π§Ή Cleaned up temporary directories")
except Exception as e:
print(f"β οΈ Cleanup warning: {e}")
def validate_models():
"""Check if essential models are available"""
essential_models = [
'/comfyui/models/unet/wan2.2_animate_14B_bf16.safetensors',
'/comfyui/models/vae/wan_2.1_vae.safetensors',
'/comfyui/models/clip/umt5_xxl_fp8_e4m3fn_scaled.safetensors',
'/comfyui/models/clip_vision/clip_vision_h.safetensors'
]
missing_models = []
for model_path in essential_models:
if not Path(model_path).exists():
missing_models.append(model_path)
if missing_models:
return False, f"Missing essential models: {', '.join(missing_models)}"
return True, "All models available"
def save_uploaded_files(input_data):
"""Save uploaded images and videos to input directory"""
images = input_data.get('images', {})
videos = input_data.get('videos', {})
saved_files = []
# Save images
for filename, base64_data in images.items():
file_path = f'/comfyui/input/{filename}'
try:
with open(file_path, 'wb') as f:
f.write(base64.b64decode(base64_data))
saved_files.append(filename)
print(f"β
Saved image: {filename}")
except Exception as e:
print(f"β Failed to save image {filename}: {e}")
# Save videos
for filename, base64_data in videos.items():
file_path = f'/comfyui/input/{filename}'
try:
with open(file_path, 'wb') as f:
f.write(base64.b64decode(base64_data))
saved_files.append(filename)
print(f"β
Saved video: {filename}")
except Exception as e:
print(f"β Failed to save video {filename}: {e}")
return saved_files
def execute_workflow(workflow, prompt_id):
"""Execute ComfyUI workflow with error handling"""
global COMFYUI_SERVER, EXECUTION_COUNT
try:
# Import ComfyUI modules
import execution
import server
import folder_paths
# Initialize server if not exists
if COMFYUI_SERVER is None:
print("π§ Initializing ComfyUI server...")
COMFYUI_SERVER = server.PromptServer.instance
# Set up paths
folder_paths.set_output_directory('/comfyui/output')
folder_paths.set_input_directory('/comfyui/input')
folder_paths.set_temp_directory('/comfyui/temp')
# Validate workflow
valid, error, unique_id = execution.validate_prompt(workflow)
if not valid:
return {
"error": f"Workflow validation failed: {error}",
"node_id": unique_id
}
# Execute workflow
executor = execution.PromptExecutor(COMFYUI_SERVER)
output_ui = {}
print(f"π Executing workflow: {prompt_id}")
executor.execute(workflow, prompt_id, {})
return {"status": "success"}
except Exception as e:
return {
"error": f"Workflow execution failed: {str(e)}",
"traceback": __import__('traceback').format_exc()
}
def collect_output_files():
"""Collect and encode output files"""
output_dir = Path('/comfyui/output')
output_files = []
if not output_dir.exists():
return output_files
# Get all video and image files
file_extensions = ['*.mp4', '*.avi', '*.mov', '*.gif', '*.png', '*.jpg', '*.jpeg']
files_found = []
for ext in file_extensions:
files_found.extend(output_dir.glob(ext))
# Sort by modification time (newest first)
files_found.sort(key=lambda x: x.stat().st_mtime, reverse=True)
for file_path in files_found[:10]: # Limit to 10 most recent files
try:
# Read and encode file (with size limit for serverless)
file_size = file_path.stat().st_size
max_size = 100 * 1024 * 1024 # 100MB limit
if file_size > max_size:
print(f"β οΈ Skipping {file_path.name} - file too large ({file_size / (1024*1024):.1f}MB)")
continue
with open(file_path, 'rb') as f:
file_data = base64.b64encode(f.read()).decode('utf-8')
output_files.append({
"filename": file_path.name,
"data": file_data,
"size": file_size,
"type": "video" if file_path.suffix.lower() in ['.mp4', '.avi', '.mov', '.gif'] else "image"
})
print(f"β
Processed output: {file_path.name} ({file_size / (1024*1024):.1f}MB)")
except Exception as e:
print(f"β Failed to process {file_path.name}: {e}")
return output_files
def handler(event):
"""
RunPod handler function
Expected input format:
{
"input": {
"workflow": {...}, # ComfyUI workflow JSON
"images": { # Optional: base64 encoded images
"filename.png": "base64_data..."
},
"videos": { # Optional: base64 encoded videos
"filename.mp4": "base64_data..."
},
"action": "execute" | "check_models" | "cleanup" # Optional action
}
}
"""
global EXECUTION_COUNT
start_time = time.time()
action = event.get('input', {}).get('action', 'execute')
try:
# Setup directories
setup_directories()
# Handle different actions
if action == "check_models":
models_valid, message = validate_models()
return {
"action": "check_models",
"models_valid": models_valid,
"message": message
}
elif action == "cleanup":
clear_directories()
return {
"action": "cleanup",
"status": "completed"
}
# Main execution path
input_data = event.get('input', {})
workflow = input_data.get('workflow', {})
if not workflow:
return {
"error": "No workflow provided"
}
# Validate models before execution
models_valid, message = validate_models()
if not models_valid:
return {
"error": f"Model validation failed: {message}"
}
# Generate prompt ID
prompt_id = str(uuid.uuid4())
# Save uploaded files
saved_files = save_uploaded_files(input_data)
print(f"π Saved {len(saved_files)} files")
# Execute workflow
result = execute_workflow(workflow, prompt_id)
if result.get("error"):
return result
# Collect output files
output_files = collect_output_files()
# Increment execution counter
EXECUTION_COUNT += 1
print(f"π Execution count: {EXECUTION_COUNT}/{MAX_EXECUTIONS_PER_INSTANCE}")
# Schedule cleanup for next request
if EXECUTION_COUNT >= MAX_EXECUTIONS_PER_INSTANCE:
clear_directories()
print("π Instance restart recommended due to execution limit")
execution_time = time.time() - start_time
print(f"β±οΈ Total execution time: {execution_time:.2f} seconds")
return {
"status": "success",
"action": "execute",
"prompt_id": prompt_id,
"output_files": output_files,
"execution_time": execution_time,
"execution_count": EXECUTION_COUNT,
"saved_files": saved_files
}
except Exception as e:
execution_time = time.time() - start_time
return {
"error": f"Handler failed: {str(e)}",
"execution_time": execution_time,
"traceback": __import__('traceback').format_exc()
}
def handler_wrapper(event):
"""Wrapper to handle RunPod serverless lifecycle"""
try:
result = handler(event)
# Add memory usage info
try:
import psutil
process = psutil.Process()
memory_info = process.memory_info()
result["memory_usage_mb"] = memory_info.rss / (1024 * 1024)
except:
pass
return result
except Exception as e:
return {
"error": f"Fatal error: {str(e)}",
"traceback": __import__('traceback').format_exc()
}
if __name__ == "__main__":
# Start RunPod serverless
print("π― Starting RunPod serverless handler...")
runpod.serverless.start({
"handler": handler_wrapper,
"return_aggregate_stream": True
})