model_loader.py
9.45 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
import os
import sys
import pickle
import marshal
import types
import logging
import torch
import numpy as np
import json
from pathlib import Path
logger = logging.getLogger('model_loader')
logger.setLevel(logging.INFO)
def load_sentiment_model(model_path, device=None):
"""
加载情感分析模型
参数:
model_path: 模型文件路径
device: 设备(可忽略,marshal模型不依赖设备)
返回:
加载好的模型对象
"""
try:
logger.info(f"加载情感分析模型: {model_path}")
if model_path.endswith('.marshal') or model_path.endswith('.marshal.3'):
with open(model_path, 'rb') as f:
model_data = marshal.load(f)
# 将marshal数据转换为可调用的函数对象
sentiment_func = types.FunctionType(model_data, globals(), "sentiment_func")
logger.info("情感分析模型加载成功")
return sentiment_func
else:
raise ValueError(f"不支持的情感模型格式: {model_path}")
except Exception as e:
logger.error(f"加载情感分析模型失败: {e}")
raise
def load_bert_ctm_model(model_dir, device='cuda' if torch.cuda.is_available() else 'cpu'):
"""
加载BERT-CTM模型
参数:
model_dir: 模型目录
device: 计算设备
返回:
包含模型和分词器的字典
"""
try:
logger.info(f"加载BERT-CTM模型: {model_dir}")
sys.path.append('model_pro')
from BERT_CTM import BERT_CTM
from transformers import BertTokenizer
# 加载模型
model_path = os.path.join(model_dir, 'final_model.pt') if not model_dir.endswith('.pt') else model_dir
model = BERT_CTM()
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
# 加载分词器
tokenizer_path = os.path.join(os.path.dirname(model_dir), 'bert_model')
tokenizer = BertTokenizer.from_pretrained(tokenizer_path)
logger.info("BERT-CTM模型加载成功")
return {
'model': model,
'tokenizer': tokenizer,
'device': device
}
except Exception as e:
logger.error(f"加载BERT-CTM模型失败: {e}")
raise
def load_bcat_model(model_dir, device='cuda' if torch.cuda.is_available() else 'cpu'):
"""
加载BCAT模型
参数:
model_dir: 模型目录
device: 计算设备
返回:
包含模型和分词器的字典
"""
try:
logger.info(f"加载BCAT模型: {model_dir}")
sys.path.append('model_pro')
from BCAT import BCAT
from transformers import BertTokenizer
# 加载模型配置
config_path = os.path.join(model_dir, 'config.json')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# 初始化模型
model = BCAT(**config)
# 加载模型权重
model_path = os.path.join(model_dir, 'model.pt')
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
# 加载分词器
tokenizer_path = os.path.join(model_dir, 'tokenizer')
tokenizer = BertTokenizer.from_pretrained(tokenizer_path)
logger.info("BCAT模型加载成功")
return {
'model': model,
'tokenizer': tokenizer,
'device': device,
'config': config
}
except Exception as e:
logger.error(f"加载BCAT模型失败: {e}")
raise
def load_topic_classifier(model_dir, device='cuda' if torch.cuda.is_available() else 'cpu'):
"""
加载话题分类模型
参数:
model_dir: 模型目录
device: 计算设备
返回:
包含模型、分词器和标签映射的字典
"""
try:
logger.info(f"加载话题分类模型: {model_dir}")
# 尝试加载transformers模型
try:
from transformers import AutoModelForSequenceClassification, AutoTokenizer
# 加载模型
model = AutoModelForSequenceClassification.from_pretrained(model_dir)
model.to(device)
model.eval()
# 加载分词器
tokenizer = AutoTokenizer.from_pretrained(model_dir)
# 加载标签映射
labels_path = os.path.join(model_dir, 'labels.json')
if os.path.exists(labels_path):
with open(labels_path, 'r', encoding='utf-8') as f:
labels_map = json.load(f)
else:
# 尝试从config中读取标签
if hasattr(model.config, 'id2label'):
labels_map = model.config.id2label
else:
labels_map = {}
logger.info("话题分类模型加载成功 (transformers)")
return {
'model': model,
'tokenizer': tokenizer,
'labels_map': labels_map,
'device': device
}
except Exception as e:
logger.warning(f"使用transformers加载失败,尝试其他方法: {e}")
# 尝试加载PyTorch模型
model_path = os.path.join(model_dir, 'model.pt')
if os.path.exists(model_path):
model = torch.load(model_path, map_location=device)
# 加载分词器
tokenizer_path = os.path.join(model_dir, 'tokenizer.pkl')
if os.path.exists(tokenizer_path):
with open(tokenizer_path, 'rb') as f:
tokenizer = pickle.load(f)
else:
tokenizer = None
# 加载标签映射
labels_path = os.path.join(model_dir, 'labels.json')
if os.path.exists(labels_path):
with open(labels_path, 'r', encoding='utf-8') as f:
labels_map = json.load(f)
else:
labels_map = {}
logger.info("话题分类模型加载成功 (PyTorch)")
return {
'model': model,
'tokenizer': tokenizer,
'labels_map': labels_map,
'device': device
}
raise ValueError(f"无法加载模型: {model_dir}")
except Exception as e:
logger.error(f"加载话题分类模型失败: {e}")
raise
def load_echarts_optimizer():
"""
加载ECharts优化器,用于提升大数据渲染性能
返回:
ECharts优化器对象
"""
try:
class EChartsOptimizer:
def __init__(self):
self.chunk_size = 1000 # 分块大小
logger.info("ECharts优化器初始化成功")
def optimize_option(self, option):
"""优化ECharts配置,提升大数据渲染性能"""
if not option:
return option
# 深拷贝以避免修改原始对象
import copy
option = copy.deepcopy(option)
# 添加渐进式渲染
if 'progressive' not in option:
option['progressive'] = 300 # 每帧渲染的数据点数量
if 'progressiveThreshold' not in option:
option['progressiveThreshold'] = 5000 # 启动渐进式渲染的阈值
if 'series' in option and isinstance(option['series'], list):
for series in option['series']:
# 对大数据系列应用优化
if 'data' in series and isinstance(series['data'], list) and len(series['data']) > 5000:
# 大数据采样
if series.get('type') in ['scatter', 'line']:
self._optimize_large_data_series(series)
return option
def _optimize_large_data_series(self, series):
"""优化大数据系列"""
# 添加大数据优化选项
series['large'] = True
series['largeThreshold'] = 2000
# 按需设置抽样
if len(series['data']) > 50000:
# 对非常大的数据集进行抽样
step = max(1, len(series['data']) // 50000)
series['data'] = series['data'][::step]
series['sampling'] = 'average'
return series
def chunk_process_data(self, data, process_func):
"""分块处理大数据"""
result = []
for i in range(0, len(data), self.chunk_size):
chunk = data[i:i + self.chunk_size]
result.extend(process_func(chunk))
return result
return EChartsOptimizer()
except Exception as e:
logger.error(f"加载ECharts优化器失败: {e}")
return None
# 导出所有加载函数
__all__ = [
'load_sentiment_model',
'load_bert_ctm_model',
'load_bcat_model',
'load_topic_classifier',
'load_echarts_optimizer'
]