-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
469 lines (450 loc) · 18.8 KB
/
main.py
File metadata and controls
469 lines (450 loc) · 18.8 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#统计工具V2.6
#切换至PyQt5模块
import sys,os
# os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'.\site-packages\PyQt5\Qt5\plugins'
# os.environ['DLL_PATH '] = r'.\AnalysisCalibInfo.dll' ####
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget,QPushButton,QComboBox,QFileDialog,QProgressBar,QTableWidget,QLineEdit,QApplication,QStyleFactory,QCheckBox,QTableWidgetItem,QDialog,QVBoxLayout,QLabel,QFrame
from PyQt5.QtGui import QIcon,QFont,QMouseEvent,QColor
from PyQt5.QtCore import QThread,pyqtSignal,Qt,QTimer
from jsonpath_ng import parse
# from CalibApi import read_calibinfo
from natsort import natsorted
import pyperclip
from Ui_ui import Ui_Form
import time
VERSION = 3.2
class Window(QWidget,Ui_Form):
def __init__(self):
super().__init__()
self.start_btn: QPushButton # 添加类型提示声明
self.path: QProgressBar # 添加类型提示声明
self.out_text: QTableWidget # 添加类型提示声明
self.progress: QLineEdit # 添加类型提示声明
self.selected: QCheckBox # 添加类型提示声明
self.sum_text: QLabel # 添加类型提示声明
self.frame_info : QFrame # 添加类型提示声明
self.frame_output : QFrame # 添加类型提示声明
self.checkBox_all : QCheckBox
self.checkBox_image : QCheckBox
self.checkBox_audio : QCheckBox
self.checkBox_video : QCheckBox
self.checkBox_txt : QCheckBox
self.checkBox_json : QCheckBox
self.checkBox_cbo : QCheckBox
self.checkBox_path : QCheckBox
self.output_class : QComboBox
self.output_btn : QPushButton
self.output_encode : QComboBox
self.set_ui()
self.initUI()
self.sort_order = "ascending"
# 初始化函数连接
self.start_btn.clicked.connect(self.start)
self.status = False
self.out_text.horizontalHeader().sectionClicked.connect(self.sort_table)
self.out_text.itemSelectionChanged.connect(self.handle_selection_change)
self.sum_text.mousePressEvent = self.label_clicked
font = QFont("微软雅黑", 9) # 设置字体为微软雅黑,字号为9
self.sum_text.setFont(font)
self.result = {}
self.count_result = {}
self.class_files = {}
self.checkBox_all.clicked.connect(self.check_all)
self.select_class_checkBox_dict = {
"json":self.checkBox_json,
"cbo":self.checkBox_cbo,
"txt":self.checkBox_txt,
"image":self.checkBox_image,
"audio":self.checkBox_audio,
"video":self.checkBox_video
}
self.total_size = 0
for i in self.select_class_checkBox_dict.values():
i.clicked.connect(self.check_select)
self.output_btn.clicked.connect(self.save_file)
def set_ui(self):
'''加载主界面Ui'''
if getattr(sys, 'frozen', None):
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(__file__)
list_ui_file = os.path.join(basedir, 'ui.ui')
# uic.loadUi(list_ui_file, self)
self.setupUi(self)
def initUI(self):
self.setWindowTitle(f"统计工具-V{VERSION}")
self.clearMain()
def check_all(self,state):
for i in self.select_class_checkBox_dict.values():
i.setChecked(state)
def check_select(self,state):
if not state:
self.checkBox_all.setChecked(state)
def save_file(self):
save_list = []
# 是否全选?
if self.checkBox_all.isChecked():
if self.checkBox_path.isChecked():
[save_list.extend(i) for i in self.class_files.values()]
else:
# [os.path.basename(file) for file_list in self.class_files.values() for file in file_list]
[save_list.append(os.path.basename(j)) for i in self.class_files.values() for j in i]
else:
for file_type in self.select_class_checkBox_dict.keys():
if not self.select_class_checkBox_dict[file_type].isChecked():continue
if self.checkBox_path.isChecked():
save_list.extend(self.class_files[file_type])
else:
[save_list.append(os.path.basename(file)) for file in self.class_files[file_type]]
if len(save_list) == 0:
self.dialog("导出文件数为0!")
return
save_type = self.output_class.currentText()
encode = self.output_encode.currentText()
# 打开输出文件对话框
if save_type == "TXT":
save_path = QFileDialog.getSaveFileName(self,'导出文件列表','output.txt',"文本文档(*.txt)")[0]
elif save_type == "CSV":
save_path = QFileDialog.getSaveFileName(self,'导出文件列表','output.csv',"逗号分割表(*.csv)")[0]
elif save_type == "XLSX":
if encode != "GBK":
self.dialog("Excel编码格式仅支持GBK,重新选择编码格式")
return
save_path = QFileDialog.getSaveFileName(self,'导出文件列表','output.xlsx',"Excel表格(*.xlsx)")[0]
if not save_path:
self.dialog("未选择保存文件路径","已取消")
return
self.save_list_to_file(save_path,save_list,save_type,encode)
def save_list_to_file(self, save_path, save_list, save_type, encode):
print(save_path, save_list.__len__(), save_type)
if save_type == "TXT" or save_type == "CSV":
with open(save_path,'w',encoding=encode) as rw:
rw.write("\n".join(save_list))
if save_type == "XLSX":
pass
def label_clicked(self, event:QMouseEvent):
value = self.sum_text.text()
values = value.split(":")
if len(values) !=2:
return
self.oldtxt=value
pyperclip.copy(values[1])
self.sum_text.setText("内容已复制")
QTimer.singleShot(1000, self.restore_label)
def restore_label(self):
self.sum_text.setText(self.oldtxt)
def clearMain(self):
self.frame_info.setVisible(False)
self.frame_output.setVisible(False)
self.out_text.clear()
self.sum_text.clear()
self.progress.setVisible(False)
self.sum_text.setVisible(False)
# 适应窗口控件高度
self.resize(320, 30)
self.result = {}
self.count_result = {}
self.sacn_files = {}
def dialog(self,message,title="Msg"):
# 创建QDialog实例
dialog = QDialog()
dialog.setWindowTitle(title)
# 关闭问号
dialog.setWindowFlags(Qt.WindowCloseButtonHint)
# 创建小部件和布局
label = QLabel(str(message))
layout = QVBoxLayout()
layout.addWidget(label)
# 创建按钮
button = QPushButton("Close")
button.clicked.connect(dialog.close)
layout.addWidget(button)
dialog.setLayout(layout)
dialog.exec_()
def start(self):
if self.status:
self.shut()
return
self.clearMain()
self.sum_text.setVisible(True)
self.resize(320,50)
path=self.path.text()
self.selected.setEnabled(False)
self.path.setEnabled(False)
if not os.path.exists(path):
self.dialog(message="路径有误或不存在")
self.start_btn.setEnabled(True)
self.selected.setEnabled(True)
self.path.setEnabled(True)
return
self.out_text.clear()
self.sum_text.clear()
self.th=ScanDir(self.path.text())
self.th.progre.connect(self.update_path)
self.th.msg.connect(self.split_file)
self.th.start()
self.sum_text.setText("1/2 正在扫描....")
self.start_btn.setText("取消")
self.status = True
def sort_table(self,index):
if self.sort_order == "ascending":
self.sort_order = "descending"
else:
self.sort_order = "ascending"
# 排序self.count_result,如果index为0,则按照"类别名称"排序,否则按照"统计数量"排序
# 按照"类别名称"排序
if index == 0:
# 根据self.sort_order进行排序
if self.sort_order == "ascending":
sorted_result = natsorted(self.result.items(), key=lambda x: x[0])
sorted_count_result = natsorted(self.count_result.items(), key=lambda x: x[0])
else:
sorted_result = natsorted(self.result.items(), key=lambda x: x[0], reverse=True)
sorted_count_result = natsorted(self.count_result.items(), key=lambda x: x[0], reverse=True)
# 按照"统计数量"排序
else:
# 根据self.sort_order进行排序
if self.sort_order == "ascending":
sorted_result = natsorted(self.result.items(), key=lambda x: x[1])
sorted_count_result = natsorted(self.count_result.items(), key=lambda x: x[1])
else:
sorted_result = natsorted(self.result.items(), key=lambda x: x[1], reverse=True)
sorted_count_result = natsorted(self.count_result.items(), key=lambda x: x[1], reverse=True)
sorted_result_data = {k:v for k,v in sorted_result}
sorted_count_result_data = {k:v for k,v in sorted_count_result}
for row,key in enumerate(sorted_count_result_data.keys()):
item = QTableWidgetItem(key)
item2 = QTableWidgetItem(str(sorted_count_result_data[key]))
self.out_text.setItem(row, 0, item)
self.out_text.setItem(row, 1, item2)
for row,key in enumerate(sorted_result_data.keys()):
row = row + len(sorted_count_result_data.keys())
item = QTableWidgetItem(key)
item2 = QTableWidgetItem(str(sorted_result_data[key]))
self.out_text.setItem(row, 0, item)
self.out_text.setItem(row, 1, item2)
def update_path(self,msg):
font = QFont("微软雅黑", 9) # 设置字体为微软雅黑,字号为9
self.sum_text.setFont(font)
path = msg.replace(self.path.text(),'')
self.sum_text.setText(f"1/2 正在扫描: {path}")
self.sum_text.setAlignment(Qt.AlignLeft) # 设置水平方向左对齐
def handle_selection_change(self):
selected_rows = self.out_text.selectionModel().selectedRows()
values=[]
for selected_row in selected_rows:
row = selected_row.row()
value = self.out_text.item(row, 1)
values.append(int(value.text()))
self.sum_text.setText("总计:{}".format(str(sum(values))))
def split_file(self,files:list):
'''
输出
'''
font = QFont("微软雅黑", 12) # 设置字体为Arial,字号为12
self.total_size = len(files)
self.sum_text.setFont(font)
self.th.terminate()
self.th = None
self.sum_text.setText("2/2 正在统计....")
self.sum_text.setAlignment(Qt.AlignHCenter) # 设置居中
self.progress.setMaximum(self.total_size)
self.progress.setMinimum(0)
isSelect=False
if self.selected.isChecked():
isSelect=True
self.th=SplitClass(files=files,isSelect=isSelect)
self.th.msg.connect(self.out)
self.th.bread.connect(self.updateProgress)
self.th.start()
self.progress.setVisible(True)
def updateProgress(self,index):
self.progress.setValue(index)
self.sum_text.setText(f"{index}/{self.total_size} 正在统计....")
def out(self,result:dict,count_result:dict,class_files:dict):
self.class_files = class_files
self.result = result
self.count_result = count_result
self.th.terminate()
self.out_text.clear()
self.out_text.setColumnCount(2)
self.out_text.setRowCount(len(result.keys()))
self.out_text.setHorizontalHeaderLabels(["类型", "数量"])
# 添加数据到表格
row = 0
for key, value in count_result.items():
key_item = QTableWidgetItem(str(key).upper())
value_item = QTableWidgetItem(str(value))
self.out_text.insertRow(row)
self.out_text.setItem(row, 0, key_item)
self.out_text.setItem(row, 1, value_item)
row += 1
for key, value in result.items():
key_item = QTableWidgetItem(str(key).upper())
value_item = QTableWidgetItem(str(value))
self.out_text.setItem(row, 0, key_item)
self.out_text.setItem(row, 1, value_item)
row += 1
self.sum_text.setText("总计:"+str(sum([int(s) for s in result.values()])))
table_height = self.out_text.rowHeight(0)*(len(result.keys())+1)
if table_height > 300:
table_height = 300
self.frame_info.setVisible(True)
self.frame_output.setVisible(True)
self.resize(320,450)
self.start_btn.setText("开始")
self.status = False
self.path.setEnabled(True)
self.selected.setEnabled(True)
self.progress.setVisible(False)
def shut(self):
'''
强制结束扫描进程
'''
self.th.terminate()
self.path.setEnabled(True)
self.selected.setEnabled(True)
self.start_btn.setText("开始")
self.status = False
self.sum_text.setVisible(False)
self.dialog(message="已终止扫描",title="已取消")
class SplitClass(QThread):
'''
分类统计结果
'''
bread=pyqtSignal(int)
msg=pyqtSignal(dict,dict,dict)
def __init__(self,files,isSelect:bool):
super().__init__()
self.files = files
self.isSelect = isSelect
self.class_files = {}
self.count_result = {}
self.result = {}
def run(self):
print("启动")
self.split_file()
def cboRead(self,path):
keys=0
try:
calibinfo = read_calibinfo(path)
except:
return 0,0
Frames=calibinfo['calibInfo']['VideoChannels'][0]['VideoInfo']['mapFrameInfos']
getTargets=parse("$[*].value.mapTargets[*].key")
mapTargets=getTargets.find(Frames)
keys=len(mapTargets)
frames=len(Frames)
return keys,frames
def split_file(self):
count_class = ["图片总数","视频总数","目标框数","结果帧数"]
audio_formats = ["MP3", "WAV", "AAC", "FLAC", "OGG", "WMA"]
video_formats = ["MP4", "AVI", "MKV", "MOV", "WMV", "FLV"]
image_formats = ["JPG", "PNG", "JPEG", "GIF", "BMP", "TIFF", "SVG"]
need_formats = [*audio_formats, *video_formats, *image_formats, "CBO", "JSON", "TXT"]
self.class_files = {
"json":[],
"cbo":[],
"txt":[],
"image":[],
"audio":[],
"video":[],
"other":[]
}
toIdx = 2 if not self.isSelect else len(count_class)
for c in count_class[:toIdx]:
self.count_result[c] = 0
index=0
for file in self.files:
# time.sleep(0.005)
try:
base_name = os.path.basename(file)
suffix = base_name.split(".")[-1].upper() if "." in base_name else "未知类型"
except Exception as e:
print(f"Error processing file {file}: {e}")
continue
if suffix in image_formats:
self.count_result["图片总数"] += 1
self.class_files['image'].append(file)
elif suffix == "JSON":
self.class_files['json'].append(file)
elif suffix == "TXT":
self.class_files['txt'].append(file)
elif suffix in audio_formats:
self.class_files['audio'].append(file)
elif suffix in video_formats:
self.count_result["视频总数"] += 1
self.class_files['video'].append(file)
elif suffix == "CBO":
self.class_files['cbo'].append(file)
if self.isSelect:
keys, frames = self.cboRead(path=file)
self.count_result["目标框数"] += keys
self.count_result["结果帧数"] += frames
else:
self.class_files['other'].append(file)
if suffix not in self.result:
self.result[suffix] = 0
index+=1
self.bread.emit(index)
self.result[suffix]+=1
self.msg.emit(self.result, self.count_result, self.class_files)
class ScanDir(QThread):
progre = pyqtSignal(str)
msg=pyqtSignal(list)
def __init__(self,directory):
super().__init__()
self.directory=directory
def run(self):
self.traverse_directory()
# 定义一个函数来遍历目录
def traverse_directory(self):
directory=self.directory
all_files=[]
for (root,_,files) in os.walk(directory):
# for file in files:
# time.sleep(0.01)
# self.progre.emit(root)
# all_files.append(os.path.join(root,file))
self.progre.emit(root)
all_files.extend([os.path.join(root,file) for file in files])
self.msg.emit(all_files)
def get_palette(app:QApplication):
dark_palette = app.palette()
dark_palette.setColor(dark_palette.Window, QColor(53, 53, 53))
dark_palette.setColor(dark_palette.WindowText, QColor(255, 255, 255))
dark_palette.setColor(dark_palette.Base, QColor(25, 25, 25))
dark_palette.setColor(dark_palette.AlternateBase, QColor(53, 53, 53))
dark_palette.setColor(dark_palette.ToolTipBase, QColor(255, 255, 255))
dark_palette.setColor(dark_palette.ToolTipText, QColor(255, 255, 255))
dark_palette.setColor(dark_palette.Text, QColor(255, 255, 255))
dark_palette.setColor(dark_palette.Button, QColor(53, 53, 53))
dark_palette.setColor(dark_palette.ButtonText, QColor(255, 255, 255))
dark_palette.setColor(dark_palette.BrightText, QColor(255, 0, 0))
dark_palette.setColor(dark_palette.Link, QColor(42, 130, 218))
dark_palette.setColor(dark_palette.Highlight, QColor(42, 130, 218))
dark_palette.setColor(dark_palette.HighlightedText, QColor(0, 0, 0))
return dark_palette
def main():
app = QApplication(sys.argv)
# Set the global application icon
if getattr(sys, 'frozen', None):
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(__file__)
icon_path = os.path.join(basedir, 'application.ico')
if not os.path.exists(icon_path):
icon_path = '.\application.ico'
app.setWindowIcon(QIcon(icon_path))
# 切换主题
app.setStyle(QStyleFactory.create("Fusion"))
# 设置 Fusion 的颜色方案为黑色
dark_palette = get_palette(app)
app.setPalette(dark_palette)
window = Window()
window.show()
app.exec_()
if __name__ == "__main__":
# 启动前检查更新
main()