Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,61 +6,74 @@ import sys
|
|
| 6 |
import base64
|
| 7 |
import os
|
| 8 |
import argparse
|
|
|
|
| 9 |
|
| 10 |
# 配置日志
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
-
class
|
| 15 |
-
def __init__(self,
|
| 16 |
-
self.
|
| 17 |
self.user_token = user_token
|
| 18 |
self.space_id = space_id
|
| 19 |
-
self.websocket = None
|
| 20 |
|
| 21 |
-
async def
|
| 22 |
-
"""
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
|
|
|
|
| 28 |
|
| 29 |
try:
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
"
|
| 37 |
-
"
|
| 38 |
-
"space_id": self.space_id
|
|
|
|
| 39 |
}
|
| 40 |
-
await websocket.send(json.dumps(auth_message))
|
| 41 |
-
logger.info("已发送认证信息")
|
| 42 |
-
|
| 43 |
-
# 等待认证响应
|
| 44 |
-
response = await websocket.recv()
|
| 45 |
-
auth_result = json.loads(response)
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
await self.upload_directory(upload_dir)
|
| 50 |
-
else:
|
| 51 |
-
logger.error(f"认证失败: {auth_result.get('message', '未知错误')}")
|
| 52 |
-
return
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
-
logger.error(f"
|
|
|
|
| 56 |
|
| 57 |
async def upload_directory(self, upload_dir):
|
| 58 |
-
"""
|
| 59 |
if not os.path.exists(upload_dir):
|
| 60 |
logger.error(f"目录不存在: {upload_dir}")
|
| 61 |
-
return
|
| 62 |
|
| 63 |
logger.info(f"🔍 开始扫描目录: {upload_dir}")
|
|
|
|
| 64 |
logger.info(f"🔑 Space ID: {self.space_id}")
|
| 65 |
logger.info("-" * 50)
|
| 66 |
|
|
@@ -74,95 +87,87 @@ class FileUploader:
|
|
| 74 |
|
| 75 |
if not all_files:
|
| 76 |
logger.info("📁 目录中没有找到任何文件")
|
| 77 |
-
|
| 78 |
-
await self.websocket.send(json.dumps({
|
| 79 |
-
"type": "upload_complete",
|
| 80 |
-
"success_count": 0,
|
| 81 |
-
"failed_count": 0
|
| 82 |
-
}))
|
| 83 |
-
return
|
| 84 |
|
| 85 |
logger.info(f"📁 找到 {len(all_files)} 个文件,开始上传...")
|
| 86 |
|
| 87 |
-
success_count = 0
|
| 88 |
-
failed_count = 0
|
| 89 |
-
|
| 90 |
-
for file_path in all_files:
|
| 91 |
-
try:
|
| 92 |
-
if await self.upload_file(file_path):
|
| 93 |
-
success_count += 1
|
| 94 |
-
else:
|
| 95 |
-
failed_count += 1
|
| 96 |
-
# 稍微延迟一下,避免发送过快
|
| 97 |
-
await asyncio.sleep(0.1)
|
| 98 |
-
except Exception as e:
|
| 99 |
-
logger.error(f"上传文件 {file_path} 时发生异常: {e}")
|
| 100 |
-
failed_count += 1
|
| 101 |
-
|
| 102 |
-
# 发送上传完成消息
|
| 103 |
-
await self.websocket.send(json.dumps({
|
| 104 |
-
"type": "upload_complete",
|
| 105 |
-
"success_count": success_count,
|
| 106 |
-
"failed_count": failed_count
|
| 107 |
-
}))
|
| 108 |
-
|
| 109 |
-
logger.info("-" * 50)
|
| 110 |
-
logger.info(f"📊 上传完成! 成功: {success_count}, 失败: {failed_count}")
|
| 111 |
-
|
| 112 |
-
if success_count > 0:
|
| 113 |
-
logger.info("🎉 文件已成功上传到您的网盘!")
|
| 114 |
-
|
| 115 |
-
return success_count, failed_count
|
| 116 |
-
|
| 117 |
-
async def upload_file(self, file_path):
|
| 118 |
-
"""上传单个文件"""
|
| 119 |
-
if not os.path.exists(file_path):
|
| 120 |
-
logger.error(f"文件不存在: {file_path}")
|
| 121 |
-
return False
|
| 122 |
-
|
| 123 |
-
filename = os.path.basename(file_path)
|
| 124 |
-
logger.info(f"正在上传文件: {filename}")
|
| 125 |
-
|
| 126 |
try:
|
| 127 |
-
with
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
"
|
| 134 |
-
"
|
| 135 |
-
"
|
| 136 |
}
|
|
|
|
| 137 |
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
-
if result.get("type") == "upload_success":
|
| 145 |
-
logger.info(f"✅ 文件 '{filename}' 上传成功!")
|
| 146 |
-
return True
|
| 147 |
-
else:
|
| 148 |
-
logger.error(f"❌ 上传失败: {result.get('message', '未知错误')}")
|
| 149 |
-
return False
|
| 150 |
-
|
| 151 |
except Exception as e:
|
| 152 |
-
logger.error(f"
|
| 153 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
|
| 156 |
parser = argparse.ArgumentParser(description="WebSocket文件上传器 - 扫描并上传指定文件夹中的所有文件")
|
| 157 |
-
parser.add_argument("user_token", help="
|
| 158 |
parser.add_argument("space_id", help="Space ID")
|
| 159 |
-
parser.add_argument("--
|
| 160 |
parser.add_argument("--upload-dir", default="output", help="要上传的目录 (默认: output)")
|
| 161 |
|
| 162 |
args = parser.parse_args()
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
| 6 |
import base64
|
| 7 |
import os
|
| 8 |
import argparse
|
| 9 |
+
import time
|
| 10 |
|
| 11 |
# 配置日志
|
| 12 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
+
class WebSocketFileUploader:
|
| 16 |
+
def __init__(self, websocket_url, user_token, space_id):
|
| 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 |
|
|
|
|
| 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 |
+
if __name__ == "__main__":
|
| 159 |
parser = argparse.ArgumentParser(description="WebSocket文件上传器 - 扫描并上传指定文件夹中的所有文件")
|
| 160 |
+
parser.add_argument("user_token", help="用户令牌 (API Key)")
|
| 161 |
parser.add_argument("space_id", help="Space ID")
|
| 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 |
args = parser.parse_args()
|
| 166 |
|
| 167 |
+
# 开始WebSocket上传
|
| 168 |
+
asyncio.run(upload_directory_websocket(
|
| 169 |
+
args.upload_dir,
|
| 170 |
+
args.websocket_url,
|
| 171 |
+
args.user_token,
|
| 172 |
+
args.space_id
|
| 173 |
+
))
|