letterm commited on
Commit
37d13d8
·
verified ·
1 Parent(s): abcdcfe

Delete protobuf_manager.py

Browse files
Files changed (1) hide show
  1. protobuf_manager.py +0 -317
protobuf_manager.py DELETED
@@ -1,317 +0,0 @@
1
- """
2
- Protobuf管理模块
3
- 提供统一的protobuf操作接口,直接使用已编译的pb2文件
4
- """
5
- import base64
6
- from typing import List, Optional, Dict, Any
7
- from utils import Utils, logger
8
-
9
- # 直接导入已编译的protobuf模块
10
- try:
11
- import warp_unified_pb2
12
- logger.success("✅ 成功导入已编译的protobuf模块")
13
- except ImportError as e:
14
- logger.error(f"❌ 无法导入protobuf模块: {e}")
15
- logger.error("请确保 warp_unified_pb2.py 文件存在且可访问")
16
- raise
17
-
18
-
19
- class ProtobufManager:
20
- """Protobuf操作管理器"""
21
-
22
- @staticmethod
23
- def create_chat_request(messages: List[Dict], model: str = "gemini-2.0-flash") -> Optional[bytes]:
24
- """
25
- 创建聊天请求的protobuf数据
26
-
27
- Args:
28
- messages: OpenAI格式的消息列表
29
- model: 模型名称
30
-
31
- Returns:
32
- 序列化的protobuf数据,如果失败返回None
33
- """
34
- try:
35
- from request_converter import RequestConverter
36
-
37
- # 处理消息历史
38
- merged_groups, current_message = RequestConverter.process_message_history(messages)
39
- logger.debug(f"🔄 处理消息历史: {len(merged_groups)} 组历史消息, 当前消息: {current_message[:50]}...")
40
-
41
- # 创建主请求
42
- request = warp_unified_pb2.ChatRequest()
43
- session_id = Utils.generate_request_id()
44
-
45
- # 如果只有一条消息,只设置当前消息
46
- if len(messages) == 1:
47
- # 字段1: 会话信息
48
- request.session.session_id = session_id
49
-
50
- # 字段2: 系统信息
51
- request.system.environment.timestamp.time = Utils.get_current_timestamp()
52
-
53
- # 当前请求信息
54
- request.system.request.content.message.text = current_message
55
- logger.debug("📝 创建单消息请求")
56
- else:
57
- # 有历史消息时,设置第一个消息组作为历史数据
58
- if merged_groups:
59
- first_content = merged_groups[0].get("content", "")
60
- request.session.history.first_message_id = session_id
61
- request.session.history.first_message_content = first_content
62
-
63
- # 添加系统消息 (固定格式)
64
- entry_a = request.session.history.entries.add()
65
- entry_a.message_id = Utils.generate_request_id()
66
- entry_a.system_msg.content_id = Utils.generate_request_id()
67
- entry_a.system_msg.metadata.data = "IgIQAQ=="
68
-
69
- # 处理剩余的消息组
70
- for message in merged_groups:
71
- if message.get("role", "") == "user":
72
- # 添加用户消息
73
- entry_b = request.session.history.entries.add()
74
- entry_b.message_id = Utils.generate_request_id()
75
- entry_b.user_msg.content = message.get("content", "")
76
- elif message.get("role", "") == "assistant":
77
- # 添加助手消息
78
- entry_c = request.session.history.entries.add()
79
- entry_c.message_id = Utils.generate_request_id()
80
- entry_c.assistant_msg.content = message.get("content", "")
81
-
82
- logger.debug(f"📚 创建多消息请求: {len(merged_groups)} 条历史消息")
83
-
84
- # 字段1: 会话信息
85
- request.session.session_id = session_id
86
-
87
- # 字段2: 系统信息
88
- request.system.environment.timestamp.time = Utils.get_current_timestamp()
89
-
90
- # 当前请求信息
91
- request.system.request.content.message.text = current_message
92
-
93
- # 字段3: AI配置
94
- request.ai_config.model.model_name = model
95
- request.ai_config.model.variant = "o3"
96
- request.ai_config.model.mode = "auto"
97
- request.ai_config.priority_level_1 = 1
98
- request.ai_config.priority_level_2 = 1
99
- request.ai_config.priority_level_3 = 1
100
- request.ai_config.priority_level_4 = 1
101
- request.ai_config.config_data = bytes([0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x02, 0x03, 0x01]).decode('utf-8')
102
-
103
- serialized = request.SerializeToString()
104
- logger.success(f"✅ 聊天请求protobuf数据序列化成功,大小: {len(serialized)} 字节")
105
-
106
- return serialized
107
-
108
- except Exception as e:
109
- logger.error(f"❌ 创建聊天请求protobuf数据时出错: {e}")
110
- import traceback
111
- traceback.print_exc()
112
- return None
113
-
114
- @staticmethod
115
- def create_login_request(login_url: str) -> Optional[bytes]:
116
- """
117
- 创建登录请求的protobuf数据
118
-
119
- Args:
120
- login_url: 登录URL
121
-
122
- Returns:
123
- 序列化的protobuf数据,如果失败返回None
124
- """
125
- try:
126
- # 创建登录请求
127
- request = warp_unified_pb2.LoginRequest()
128
-
129
- # 设置请求标志
130
- request.request_flags.extend([9, 18, 20, 21, 31, 35])
131
- request.request_type = 2
132
-
133
- # 设置登录URL
134
- request.login_data.url = login_url
135
-
136
- # 设置配置标志
137
- request.config_flags.extend([3, 2])
138
-
139
- # 设置语言
140
- request.language = "zh-CN"
141
-
142
- # 设置请求设置
143
- request.settings.setting_value = 6
144
-
145
- # 序列化
146
- serialized = request.SerializeToString()
147
- logger.debug(f"🔄 登录请求protobuf序列化成功,数据长度: {len(serialized)} 字节")
148
- return serialized
149
-
150
- except Exception as e:
151
- logger.error(f"❌ 创建登录请求protobuf数据时出错: {e}")
152
- return None
153
-
154
- @staticmethod
155
- def parse_chat_response(base64_data: str) -> str:
156
- """
157
- 解析聊天响应的protobuf数据
158
-
159
- Args:
160
- base64_data: base64编码的响应数据
161
-
162
- Returns:
163
- 解析后的文本内容
164
- """
165
- try:
166
- response = warp_unified_pb2.ChatResponse()
167
- b64_data = base64.urlsafe_b64decode(base64_data)
168
- response.ParseFromString(b64_data)
169
-
170
- # 尝试从主要响应中获取文本
171
- if hasattr(response.metadata.content, 'primary') and response.metadata.content.primary.text.content.text:
172
- text = response.metadata.content.primary.text.content.text
173
- logger.debug(f"📥 解析主响应文本: {len(text)} 字符")
174
- return text
175
-
176
- # 尝试从备用响应中获取文本
177
- if hasattr(response.metadata.content, 'secondary') and response.metadata.content.secondary.alternative.final_content.text:
178
- text = response.metadata.content.secondary.alternative.final_content.text
179
- logger.debug(f"📥 解析备用响应文本: {len(text)} 字符")
180
- return text
181
-
182
- logger.debug("⚠️ 响应中未找到文本内容")
183
- return ""
184
-
185
- except Exception as e:
186
- logger.error(f"❌ 解析聊天响应protobuf数据时出错: {e}")
187
- return ""
188
-
189
- @staticmethod
190
- def parse_login_response(response_content: bytes) -> str:
191
- """
192
- 解析登录响应的protobuf数据
193
-
194
- Args:
195
- response_content: 响应的二进制内容
196
-
197
- Returns:
198
- 解析后的登录URL
199
- """
200
- try:
201
- import urllib.parse
202
-
203
- parsed_data = warp_unified_pb2.LoginRequest()
204
- parsed_data.ParseFromString(response_content)
205
-
206
- # 提取嵌套的URL
207
- parsed_data_url = parsed_data.url_chain.container_2.container_3.container_4.container_5.container_6.url_container.final_url.login_url
208
- logger.info(f"🔄 解析后的URL: {parsed_data_url}")
209
-
210
- decoded_url = urllib.parse.unquote(parsed_data_url)
211
- logger.info(f"🔄 解码后的URL: {decoded_url}")
212
-
213
- return decoded_url
214
-
215
- except Exception as e:
216
- logger.error(f"❌ 解析登录响应protobuf数据时出错: {e}")
217
- return ""
218
-
219
- @staticmethod
220
- def get_protobuf_classes() -> Dict[str, Any]:
221
- """
222
- 获取所有可用的protobuf类
223
-
224
- Returns:
225
- 包含所有protobuf类的字典
226
- """
227
- return {
228
- 'ChatRequest': warp_unified_pb2.ChatRequest,
229
- 'ChatResponse': warp_unified_pb2.ChatResponse,
230
- 'LoginRequest': warp_unified_pb2.LoginRequest,
231
- 'SessionInfo': warp_unified_pb2.SessionInfo,
232
- 'MessageHistory': warp_unified_pb2.MessageHistory,
233
- 'MessageEntry': warp_unified_pb2.MessageEntry,
234
- 'SystemInfo': warp_unified_pb2.SystemInfo,
235
- 'AIConfig': warp_unified_pb2.AIConfig,
236
- 'ModelConfig': warp_unified_pb2.ModelConfig,
237
- 'LoginData': warp_unified_pb2.LoginData,
238
- 'RequestSettings': warp_unified_pb2.RequestSettings,
239
- }
240
-
241
- @staticmethod
242
- def create_empty_request(request_type: str) -> Optional[Any]:
243
- """
244
- 创建空的protobuf请求对象
245
-
246
- Args:
247
- request_type: 请求类型 ('chat' 或 'login')
248
-
249
- Returns:
250
- 对应的protobuf请求对象
251
- """
252
- try:
253
- if request_type.lower() == 'chat':
254
- return warp_unified_pb2.ChatRequest()
255
- elif request_type.lower() == 'login':
256
- return warp_unified_pb2.LoginRequest()
257
- else:
258
- logger.error(f"❌ 不支持的请求类型: {request_type}")
259
- return None
260
- except Exception as e:
261
- logger.error(f"❌ 创建空请求对象时出错: {e}")
262
- return None
263
-
264
- @staticmethod
265
- def validate_protobuf_module() -> bool:
266
- """
267
- 验证protobuf模块是否正确加载
268
-
269
- Returns:
270
- 如果模块正确加载返回True,否则返回False
271
- """
272
- try:
273
- # 测试创建基本对象
274
- chat_request = warp_unified_pb2.ChatRequest()
275
- login_request = warp_unified_pb2.LoginRequest()
276
-
277
- # 测试基本序列化
278
- chat_request.session.session_id = "test"
279
- serialized = chat_request.SerializeToString()
280
-
281
- if len(serialized) > 0:
282
- logger.success("✅ Protobuf模块验证通过")
283
- return True
284
- else:
285
- logger.error("❌ Protobuf模块验证失败:序列化结果为空")
286
- return False
287
-
288
- except Exception as e:
289
- logger.error(f"❌ Protobuf模块验证失败: {e}")
290
- return False
291
-
292
-
293
- # 模块级别的便捷函数
294
- def create_chat_protobuf(messages: List[Dict], model: str = "gemini-2.0-flash") -> Optional[bytes]:
295
- """便捷函数:创建聊天请求protobuf数据"""
296
- return ProtobufManager.create_chat_request(messages, model)
297
-
298
-
299
- def create_login_protobuf(login_url: str) -> Optional[bytes]:
300
- """便捷函数:创建登录请求protobuf数据"""
301
- return ProtobufManager.create_login_request(login_url)
302
-
303
-
304
- def parse_chat_protobuf(base64_data: str) -> str:
305
- """便捷函数:解析聊天响应protobuf数据"""
306
- return ProtobufManager.parse_chat_response(base64_data)
307
-
308
-
309
- def parse_login_protobuf(response_content: bytes) -> str:
310
- """便捷函数:解析登录响应protobuf数据"""
311
- return ProtobufManager.parse_login_response(response_content)
312
-
313
-
314
- # 在模块加载时验证protobuf模块
315
- if __name__ != "__main__":
316
- if not ProtobufManager.validate_protobuf_module():
317
- logger.warning("⚠️ Protobuf模块验证失败,某些功能可能不可用")