-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfastapi_callback_server.py
More file actions
393 lines (315 loc) · 11.6 KB
/
fastapi_callback_server.py
File metadata and controls
393 lines (315 loc) · 11.6 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env python3
"""
ComfyUI FastAPI 回调服务器
支持图片回调和视频回调的 FastAPI 服务器
端口: 6688
"""
import json
import time
import os
import socket
from datetime import datetime
from typing import List, Optional, Dict, Any
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
# 数据模型
class ImageCallbackData(BaseModel):
"""图片回调数据模型"""
task_uuid: str
message: str
images: List[str]
comfyui_images: List[str]
class VideoCallbackData(BaseModel):
"""视频回调数据模型"""
task_uuid: str
message: str
videos: List[str]
comfyui_videos: List[str]
class CallbackResponse(BaseModel):
"""回调响应模型"""
status: str
message: str
timestamp: float
class ServerStatus(BaseModel):
"""服务器状态模型"""
server: str
status: str
port: int
timestamp: float
uptime: float
total_callbacks: int
# 全局变量
app = FastAPI(
title="ComfyUI Callback Server",
description="支持图片和视频回调的 FastAPI 服务器",
version="1.0.0"
)
# 添加CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 服务器状态
server_start_time = time.time()
total_callbacks = 0
@app.get("/", response_class=HTMLResponse)
async def root():
"""根路径 - 返回简单的HTML页面"""
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>ComfyUI FastAPI Callback Server</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.container { max-width: 800px; margin: 0 auto; }
.status { background: #f0f0f0; padding: 20px; border-radius: 5px; margin: 20px 0; }
.endpoint { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 10px 0; }
.code { background: #f5f5f5; padding: 10px; border-radius: 3px; font-family: monospace; }
</style>
</head>
<body>
<div class="container">
<h1>🎨 ComfyUI FastAPI 回调服务器</h1>
<p>支持图片和视频回调的 FastAPI 服务器</p>
<div class="status">
<h3>📊 服务器状态</h3>
<p>端口: 6688</p>
<p>状态: <a href="/status">查看详细状态</a></p>
<p>API文档: <a href="/docs">Swagger UI</a></p>
<p>日志目录: callback_logs/</p>
</div>
<div class="endpoint">
<h3>🖼️ 图片回调</h3>
<p><strong>POST</strong> /images_callback</p>
<div class="code">
{
"task_uuid": "task-12345-abcde",
"message": "图片处理完成",
"images": ["path/to/image1.png", "path/to/image2.png"]
}
</div>
</div>
<div class="endpoint">
<h3>🎬 视频回调</h3>
<p><strong>POST</strong> /videos_callback</p>
<div class="code">
{
"task_uuid": "task-12345-abcde",
"message": "视频处理完成",
"videos": ["path/to/video1.mp4", "path/to/video2.mp4"]
}
</div>
</div>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.get("/status", response_model=ServerStatus)
async def get_status():
"""获取服务器状态"""
global total_callbacks
return ServerStatus(
server="ComfyUI FastAPI Callback Server",
status="running",
port=6688,
timestamp=time.time(),
uptime=time.time() - server_start_time,
total_callbacks=total_callbacks
)
@app.post("/images_callback", response_model=CallbackResponse)
async def images_callback(data: ImageCallbackData, request: Request):
"""处理图片回调请求"""
global total_callbacks
total_callbacks += 1
try:
# 处理回调数据
await handle_callback_data("images", data.model_dump(), request)
return CallbackResponse(
status="success",
message="图片回调处理成功",
timestamp=time.time()
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"处理图片回调时出错: {str(e)}")
@app.post("/videos_callback", response_model=CallbackResponse)
async def videos_callback(data: VideoCallbackData, request: Request):
"""处理视频回调请求"""
global total_callbacks
total_callbacks += 1
try:
# 处理回调数据
await handle_callback_data("videos", data.model_dump(), request)
return CallbackResponse(
status="success",
message="视频回调处理成功",
timestamp=time.time()
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"处理视频回调时出错: {str(e)}")
async def handle_callback_data(callback_type: str, data: Dict[str, Any], request: Request):
"""处理回调数据的通用函数"""
try:
# 提取回调信息
task_uuid = data.get('task_uuid', 'unknown')
message = data.get('message', '')
files = data.get('images' if callback_type == 'images' else 'videos', [])
# 获取客户端IP
client_ip = request.client.host if request.client else "unknown"
print(json.dumps(data, ensure_ascii=False, indent=2))
# 打印回调信息
print(f"\n{'='*60}")
print(f"[FastAPI回调服务器] 收到{callback_type}回调请求")
print(f"[FastAPI回调服务器] 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"[FastAPI回调服务器] 客户端IP: {client_ip}")
print(f"[FastAPI回调服务器] 任务UUID: {task_uuid}")
print(f"[FastAPI回调服务器] 消息: {message}")
print(f"[FastAPI回调服务器] 文件数量: {len(files)}")
print(f"{'='*60}\n")
# 保存回调记录到文件
await save_callback_record(callback_type, data, client_ip)
except Exception as e:
print(f"[FastAPI回调服务器] 处理{callback_type}回调数据时出错: {str(e)}")
raise
async def save_callback_record(callback_type: str, data: Dict[str, Any], client_ip: str):
"""保存回调记录到文件"""
try:
# 创建日志目录
log_dir = "callback_logs"
os.makedirs(log_dir, exist_ok=True)
# 生成日志文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
task_uuid = data.get('task_uuid', 'unknown')
log_filename = f"{log_dir}/{callback_type}_callback_{task_uuid}_{timestamp}.json"
# 添加服务器信息到数据中
record_data = data.copy()
record_data['callback_type'] = callback_type
record_data['received_at'] = datetime.now().isoformat()
record_data['server_timestamp'] = time.time()
record_data['client_ip'] = client_ip
# 保存到文件
with open(log_filename, 'w', encoding='utf-8') as f:
json.dump(record_data, f, ensure_ascii=False, indent=2)
print(f"[FastAPI回调服务器] {callback_type}回调记录已保存: {log_filename}")
except Exception as e:
print(f"[FastAPI回调服务器] 保存{callback_type}回调记录时出错: {str(e)}")
@app.get("/logs")
async def get_logs():
"""获取日志文件列表"""
try:
log_dir = "callback_logs"
if not os.path.exists(log_dir):
return {"logs": [], "message": "日志目录不存在"}
log_files = []
for filename in os.listdir(log_dir):
if filename.endswith('.json'):
file_path = os.path.join(log_dir, filename)
file_stat = os.stat(file_path)
log_files.append({
"filename": filename,
"size": file_stat.st_size,
"modified": datetime.fromtimestamp(file_stat.st_mtime).isoformat()
})
# 按修改时间排序
log_files.sort(key=lambda x: x['modified'], reverse=True)
return {
"logs": log_files,
"total": len(log_files),
"directory": log_dir
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"获取日志列表时出错: {str(e)}")
@app.get("/logs/{filename}")
async def get_log_content(filename: str):
"""获取指定日志文件内容"""
try:
log_dir = "callback_logs"
file_path = os.path.join(log_dir, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="日志文件不存在")
with open(file_path, 'r', encoding='utf-8') as f:
content = json.load(f)
return content
except Exception as e:
raise HTTPException(status_code=500, detail=f"读取日志文件时出错: {str(e)}")
def get_local_ip():
"""获取本机IP地址"""
try:
# 创建一个socket连接来获取本机IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
try:
# 备用方法
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
return ip
except Exception:
return "127.0.0.1"
def print_server_info():
"""打印服务器信息"""
local_ip = get_local_ip()
port = 6688
print("🎨 ComfyUI FastAPI 回调服务器")
print("=" * 80)
print("支持图片和视频回调的 FastAPI 服务器")
print("=" * 80)
print(f"📡 服务器地址:")
print(f" 本机IP: {local_ip}")
print(f" 端口: {port}")
print()
print(f"🌐 访问链接:")
print(f" 主页: http://localhost:{port}/")
print(f" 主页: http://{local_ip}:{port}/")
print()
print(f"📚 API 接口:")
print(f" API文档: http://localhost:{port}/docs")
print(f" API文档: http://{local_ip}:{port}/docs")
print()
print(f"📊 状态接口:")
print(f" 服务器状态: http://localhost:{port}/status")
print(f" 服务器状态: http://{local_ip}:{port}/status")
print()
print(f"🖼️ 图片回调:")
print(f" POST http://localhost:{port}/images_callback")
print(f" POST http://{local_ip}:{port}/images_callback")
print()
print(f"🎬 视频回调:")
print(f" POST http://localhost:{port}/videos_callback")
print(f" POST http://{local_ip}:{port}/videos_callback")
print()
print(f"📋 日志接口:")
print(f" 日志列表: http://localhost:{port}/logs")
print(f" 日志列表: http://{local_ip}:{port}/logs")
print(f" 日志详情: http://localhost:{port}/logs/{{filename}}")
print(f" 日志详情: http://{local_ip}:{port}/logs/{{filename}}")
print()
print(f"📁 日志目录: callback_logs/")
print("=" * 80)
print("按 Ctrl+C 停止服务器")
print("=" * 80)
def main():
"""主函数"""
# 打印服务器信息
print_server_info()
# 启动服务器
uvicorn.run(
"fastapi_callback_server:app",
host="0.0.0.0",
port=6688,
reload=False,
log_level="info"
)
if __name__ == "__main__":
main()