Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,173 +1,32 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
import os
|
8 |
-
import argparse
|
9 |
-
import time
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
self.websocket_url = websocket_url
|
18 |
-
self.user_token = user_token
|
19 |
-
self.space_id = space_id
|
20 |
-
|
21 |
-
async def upload_file(self, websocket, file_path):
|
22 |
-
"""上传单个文件"""
|
23 |
-
if not os.path.exists(file_path):
|
24 |
-
logger.error(f"文件不存在: {file_path}")
|
25 |
-
return False
|
26 |
-
|
27 |
-
filename = os.path.basename(file_path)
|
28 |
-
logger.info(f"正在上传文件: {filename}")
|
29 |
-
|
30 |
-
try:
|
31 |
-
with open(file_path, 'rb') as f:
|
32 |
-
file_content = f.read()
|
33 |
-
file_b64 = base64.b64encode(file_content).decode('utf-8')
|
34 |
-
|
35 |
-
file_msg = {
|
36 |
-
"type": "file_upload",
|
37 |
-
"filename": filename,
|
38 |
-
"content": file_b64,
|
39 |
-
"space_id": self.space_id,
|
40 |
-
"user_token": self.user_token
|
41 |
-
}
|
42 |
-
|
43 |
-
await websocket.send(json.dumps(file_msg))
|
44 |
-
logger.info(f"已发送文件: {filename}")
|
45 |
-
|
46 |
-
# 等待服务器响应
|
47 |
-
try:
|
48 |
-
response = await asyncio.wait_for(websocket.recv(), timeout=30.0)
|
49 |
-
data = json.loads(response)
|
50 |
-
|
51 |
-
if data.get("type") == "upload_success":
|
52 |
-
logger.info(f"✅ 文件 '{filename}' 上传成功!")
|
53 |
-
return True
|
54 |
-
elif data.get("type") == "upload_error":
|
55 |
-
logger.error(f"❌ 上传失败: {data.get('message', '未知错误')}")
|
56 |
-
return False
|
57 |
-
else:
|
58 |
-
logger.warning(f"收到未知响应: {data}")
|
59 |
-
return False
|
60 |
-
|
61 |
-
except asyncio.TimeoutError:
|
62 |
-
logger.error(f"上传文件 {filename} 超时")
|
63 |
-
return False
|
64 |
-
|
65 |
-
except Exception as e:
|
66 |
-
logger.error(f"上传文件 {file_path} 时出错: {e}")
|
67 |
-
return False
|
68 |
-
|
69 |
-
async def upload_directory(self, upload_dir):
|
70 |
-
"""上传目录中的所有文件"""
|
71 |
-
if not os.path.exists(upload_dir):
|
72 |
-
logger.error(f"目录不存在: {upload_dir}")
|
73 |
-
return 0, 0
|
74 |
-
|
75 |
-
logger.info(f"🔍 开始扫描目录: {upload_dir}")
|
76 |
-
logger.info(f"📡 WebSocket服务器: {self.websocket_url}")
|
77 |
-
logger.info(f"🔑 Space ID: {self.space_id}")
|
78 |
-
logger.info("-" * 50)
|
79 |
-
|
80 |
-
# 获取所有文件
|
81 |
-
all_files = []
|
82 |
-
for root, dirs, files in os.walk(upload_dir):
|
83 |
-
for file in files:
|
84 |
-
file_path = os.path.join(root, file)
|
85 |
-
if os.path.isfile(file_path):
|
86 |
-
all_files.append(file_path)
|
87 |
-
|
88 |
-
if not all_files:
|
89 |
-
logger.info("📁 目录中没有找到任何文件")
|
90 |
-
return 0, 0
|
91 |
-
|
92 |
-
logger.info(f"📁 找到 {len(all_files)} 个文件,开始上传...")
|
93 |
-
|
94 |
-
try:
|
95 |
-
async with websockets.connect(
|
96 |
-
self.websocket_url,
|
97 |
-
ping_interval=20,
|
98 |
-
ping_timeout=60,
|
99 |
-
close_timeout=10
|
100 |
-
) as websocket:
|
101 |
-
logger.info("WebSocket连接已建立")
|
102 |
-
|
103 |
-
# 发送认证信息
|
104 |
-
auth_msg = {
|
105 |
-
"type": "auth",
|
106 |
-
"user_token": self.user_token,
|
107 |
-
"space_id": self.space_id
|
108 |
-
}
|
109 |
-
await websocket.send(json.dumps(auth_msg))
|
110 |
-
|
111 |
-
# 等待认证响应
|
112 |
-
try:
|
113 |
-
auth_response = await asyncio.wait_for(websocket.recv(), timeout=10.0)
|
114 |
-
auth_data = json.loads(auth_response)
|
115 |
-
|
116 |
-
if auth_data.get("type") != "auth_success":
|
117 |
-
logger.error(f"认证失败: {auth_data.get('message', '未知错误')}")
|
118 |
-
return 0, len(all_files)
|
119 |
-
|
120 |
-
logger.info("认证成功,开始上传文件")
|
121 |
-
|
122 |
-
except asyncio.TimeoutError:
|
123 |
-
logger.error("认证超时")
|
124 |
-
return 0, len(all_files)
|
125 |
-
|
126 |
-
success_count = 0
|
127 |
-
failed_count = 0
|
128 |
-
|
129 |
-
for file_path in all_files:
|
130 |
-
try:
|
131 |
-
if await self.upload_file(websocket, file_path):
|
132 |
-
success_count += 1
|
133 |
-
else:
|
134 |
-
failed_count += 1
|
135 |
-
# 稍微延迟一下,避免服务器压力过大
|
136 |
-
await asyncio.sleep(0.5)
|
137 |
-
except Exception as e:
|
138 |
-
logger.error(f"上传文件 {file_path} 时发生异常: {e}")
|
139 |
-
failed_count += 1
|
140 |
-
|
141 |
-
logger.info("-" * 50)
|
142 |
-
logger.info(f"📊 上传完成! 成功: {success_count}, 失败: {failed_count}")
|
143 |
-
|
144 |
-
if success_count > 0:
|
145 |
-
logger.info("🎉 文件已成功上传到您的网盘!")
|
146 |
-
|
147 |
-
return success_count, failed_count
|
148 |
-
|
149 |
-
except Exception as e:
|
150 |
-
logger.error(f"WebSocket连接失败: {e}")
|
151 |
-
return 0, len(all_files)
|
152 |
-
|
153 |
-
async def upload_directory_websocket(upload_dir, websocket_url, user_token, space_id):
|
154 |
-
"""使用WebSocket上传目录中的所有文件"""
|
155 |
-
uploader = WebSocketFileUploader(websocket_url, user_token, space_id)
|
156 |
-
return await uploader.upload_directory(upload_dir)
|
157 |
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
parser.add_argument("--websocket-url", default="ws://127.0.0.1:5001/ws", help="WebSocket服务器地址 (默认: ws://127.0.0.1:5001/ws)")
|
163 |
-
parser.add_argument("--upload-dir", default="output", help="要上传的目录 (默认: output)")
|
164 |
|
165 |
-
|
|
|
166 |
|
167 |
-
#
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
from diffusers import DiffusionPipeline, AutoencoderKL
|
5 |
+
from PIL import Image
|
6 |
+
import re
|
|
|
|
|
|
|
7 |
|
8 |
+
def generate_image(pipe, prompt, seed=42, randomize_seed=True, width=768, height=768, guidance_scale=4.5, num_inference_steps=20):
|
9 |
+
"""
|
10 |
+
使用 FLUX.1-Krea-dev 模型生成图像。
|
11 |
|
12 |
+
Args:
|
13 |
+
pipe: 配置好的 Diffusers pipeline.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
prompt (str): 文本提示.
|
16 |
+
seed (int): 随机种子.
|
17 |
+
randomize_seed (bool): 是否随机化种子.
|
18 |
+
generator = torch.Generator(device=pipe.device).manual_seed(seed)
|
|
|
|
|
19 |
|
20 |
+
print(f"ℹ️ 使用种子: {seed}")
|
21 |
+
print("🚀 开始生成图像...")
|
22 |
|
23 |
+
# 直接调用 pipeline 生成 PIL 图像,内部会自动处理解码
|
24 |
+
image = pipe(
|
25 |
+
prompt=prompt,
|
26 |
+
guidance_scale=guidance_scale,
|
27 |
+
num_inference_steps=num_inference_steps,
|
28 |
+
width=width,
|
29 |
+
height=height,
|
30 |
+
generator=generator,
|
31 |
+
output_type="pil"
|
32 |
+
).images[0]
|