-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrice_websocket.py
More file actions
283 lines (252 loc) · 9.92 KB
/
rice_websocket.py
File metadata and controls
283 lines (252 loc) · 9.92 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
import datetime
from enum import Enum
import json
import time
import threading
from typing import Any, Callable, Optional
import asyncio
import websockets
from websockets.exceptions import ConnectionClosedError
import comfy.model_management as model_management
COMMAND_TYPE_USER_SERVER_TASK_PROGRESS = 5004
COMMAND_TYPE_USER_CLIENT_WEB_COMMAND_CANCEL_TASK = 4002
class TaskStatus(Enum):
CREATED = 0
PENDING = 1
IN_PROGRESS = 2
FINISHED = 3
FAILED = 4
CANCELLED = 5
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
def __le__(self, other):
if self.__class__ is other.__class__:
return self.value <= other.value
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented
def __ge__(self, other):
if self.__class__ is other.__class__:
return self.value >= other.value
return NotImplemented
class TaskInfo:
def __init__(self, json_data):
self.task_uuid = json_data.get("task_uuid", "")
self.state = TaskStatus(json_data.get("state", 0))
self.progress = json_data.get("progress", 0)
self.progress_text = json_data.get("progress_text", "")
self.thumbnail = json_data.get("thumbnail", "")
self.prompt = json_data.get("prompt", "")
self.create_time = json_data.get("create_time", "")
self.update_time = json_data.get("update_time", "")
self.template_id = json_data.get("template_id", "")
self.template_description = json_data.get("template_description", "")
self.template_name = json_data.get("template_name", "")
self.result_data = json_data.get("result_data", None)
self.lock = threading.Lock()
self.preview_refreshed = False
def to_dict(self):
return {
"task_uuid": self.task_uuid,
"state": self.state.value,
"progress": self.progress,
"progress_text": self.progress_text,
"thumbnail": self.thumbnail,
"prompt": self.prompt,
"create_time": self.create_time,
"update_time": self.update_time,
"template_id": self.template_id,
"template_description": self.template_description,
"template_name": self.template_name,
}
def update_progress(self, json_data):
with self.lock:
if json_data.get("task_uuid", "") != self.task_uuid:
return False
state = TaskStatus(json_data.get("state", 0))
if state < self.state:
return False
self.state = state
progress = json_data.get("progress", 0)
progress_text = json_data.get("progress_text", "")
if progress == 0 and progress_text == "preview_refreshed":
print(f"Task {self.task_uuid} preview_refreshed")
self.preview_refreshed = True
else:
self.preview_refreshed = False
if progress > self.progress:
self.progress = progress
self.progress_text = progress_text
elif state == TaskStatus.FAILED:
self.progress_text = (
progress_text if progress_text else "task failed"
)
elif state == TaskStatus.CANCELLED:
self.progress_text = (
progress_text if progress_text else "task cancelled"
)
else:
return False
result_data = json_data.get("result_data", None)
if result_data:
self.result_data = result_data
elif self.state == TaskStatus.IN_PROGRESS:
self.result_data = None
return True
def is_task_done(self):
with self.lock:
return self.state >= TaskStatus.FINISHED
def __str__(self):
return f"Task {self.task_uuid}: {self.state.name} ({self.progress}%) - {self.progress_text}"
class PackageMessage:
def __init__(self, CommandType, Message):
self.CommandType = CommandType
self.Message = Message
def to_json(self):
return json.dumps({"CommandType": self.CommandType, "Message": self.Message})
@classmethod
def from_json(cls, data):
parsed = json.loads(data)
return cls(parsed["CommandType"], parsed["Message"])
class TaskWebSocket:
def __init__(
self, url, token, machine_id, task_info, progress_callback, timeout=600
):
self.url = f"{url}?machine_id={machine_id}"
self.token = token
self.task_info = task_info
self.stop_event = asyncio.Event()
self.timeout = timeout
self.progress_callback = progress_callback
self.last_progress_time = None
self.message_timeout = timeout - 3 if timeout < 600 else 600
self.websocket = None
self.task = None
async def connect(self):
try:
ws_url = f"{self.url}&token={self.token}"
async with websockets.connect(ws_url) as websocket:
self.websocket = websocket
await self.on_connection_open()
await self.run_tasks()
except Exception as e:
print(f"Connection error: {e}")
async def run_tasks(self):
try:
receive_task = asyncio.create_task(self.on_receive())
monitor_task = asyncio.create_task(self.monitor_progress_timeout())
done, pending = await asyncio.wait(
[receive_task, monitor_task],
timeout=self.timeout,
return_when=asyncio.FIRST_COMPLETED,
)
self.stop_event.set()
for task in pending:
print(f"cancel task {task}")
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
finally:
self.stop_event.set()
async def on_receive(self):
try:
if not self.websocket or self.stop_event.is_set():
return
async for message in self.websocket:
if self.stop_event.is_set():
break
await self.on_message(message)
except Exception as e:
print(f"Error while listening to messages: {e}")
async def monitor_progress_timeout(self):
while not self.stop_event.is_set():
await asyncio.sleep(5)
try:
model_management.throw_exception_if_processing_interrupted()
except Exception as e:
print(f"Processing interrupted during progress monitoring: {e}")
self.stop_event.set()
cancel_message = PackageMessage(
CommandType=COMMAND_TYPE_USER_CLIENT_WEB_COMMAND_CANCEL_TASK,
Message={"task_uuid": self.task_info.task_uuid},
)
try:
await self.send_message(cancel_message)
except Exception as send_err:
print(f"Failed to send cancel notification: {send_err}")
break
current_time = asyncio.get_event_loop().time()
if (
self.last_progress_time
and current_time - self.last_progress_time > self.message_timeout
):
print(
f"No task progress received within {self.message_timeout} seconds, disconnecting..."
)
self.stop_event.set()
break
async def on_message(self, message):
try:
package = PackageMessage.from_json(message)
if package.CommandType == COMMAND_TYPE_USER_SERVER_TASK_PROGRESS:
await self.handle_task_progress(package)
else:
print(f"Unknown message type: {package.CommandType}")
except Exception as e:
print(f"Message unpacking error: {e}")
async def on_connection_open(self):
print("WebSocket connection connected")
async def send_message(self, message):
try:
if self.websocket:
await self.websocket.send(message.to_json())
except Exception as e:
print(f"Error sending message: {e}")
async def handle_task_progress(self, package):
if not self.task_info or self.stop_event.is_set():
return
loop = asyncio.get_event_loop()
self.last_progress_time = loop.time()
if self.task_info.update_progress(package.Message):
print(f"Task progress updated: {self.task_info}")
if self.progress_callback:
self.progress_callback(
self.task_info.task_uuid,
self.task_info.progress_text,
self.task_info.progress,
self.task_info.preview_refreshed,
)
if self.task_info.is_task_done():
print("task is done")
self.stop_event.set()
async def shutdown(self):
print("shutdown websocket")
self.stop_event.set()
self.progress_callback = None
if self.websocket:
try:
await self.websocket.close()
except websockets.ConnectionClosed:
pass
finally:
self.websocket = None
def start_and_wait_task_done(
task_ws_url, user_token, machine_id, task_info, progress_callback, timeout=7200
):
async def main():
task_ws = TaskWebSocket(
task_ws_url, user_token, machine_id, task_info, progress_callback, timeout
)
try:
await task_ws.connect()
except asyncio.CancelledError:
print("Task cancelled")
finally:
await task_ws.shutdown()
asyncio.run(main())