Repository navigation
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
2419 lines (2094 loc) · 102 KB
/
Copy pathmainwindow.cpp
File metadata and controls
2419 lines (2094 loc) · 102 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDir>
#include <QFileInfo>
#include <QStandardPaths>
#include <QDebug>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QRegularExpression>
#include <QApplication>
#include <QCoreApplication>
#include <QSettings>
#include <QTimer>
#include <QIcon>
#include <QFileDialog>
#include <QListWidget>
#include <QListWidgetItem>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QFormLayout>
#include <QScrollArea>
#include <QSplitter>
#include <QProgressDialog>
#include <QProcess>
#include <QTimer>
#ifdef HAVE_OPENCV
#include <opencv2/opencv.hpp>
#endif
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 設置視窗圖標 / Set window icon
setWindowIcon(QIcon(":/icon/raw.png"));
// 連接信號槽 / Connect signals and slots
connect(ui->pythonComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::onPythonComboBoxChanged);
connect(ui->venvComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::onVenvComboBoxChanged);
connect(ui->selectEnvButton, &QPushButton::clicked,
this, &MainWindow::onSelectEnvButtonClicked);
connect(ui->refreshButton, &QPushButton::clicked,
this, &MainWindow::onRefreshButtonClicked);
// 檢查並安裝 OpenCV / Check and install OpenCV
#ifdef HAVE_OPENCV
// OpenCV is available at compile time, no need to check
#else
// OpenCV was not compiled in, check if it's installed and offer to install
if (!checkOpenCVInstalled()) {
QMessageBox::StandardButton reply = QMessageBox::question(this,
"OpenCV Not Available",
"OpenCV is not available in this build.\n\n"
"This application was compiled without OpenCV support. "
"To use image processing features, you need to:\n\n"
"1. Install OpenCV (if not already installed)\n"
"2. Rebuild the application with OpenCV enabled\n\n"
"Would you like to install OpenCV now?\n"
"(You will still need to rebuild the application after installation)",
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
if (reply == QMessageBox::Yes) {
installOpenCV();
}
} else {
// OpenCV is installed but not compiled in
QMessageBox::information(this,
"OpenCV Installed But Not Available",
"OpenCV is installed on your system, but this application was compiled without OpenCV support.\n\n"
"To use image processing features, please rebuild the application:\n\n"
"1. Run CMake configuration again\n"
"2. CMake should detect OpenCV automatically\n"
"3. Rebuild the application\n\n"
"Image processing features will be disabled until you rebuild.");
}
#endif
// 掃描 Python 環境 / Scan Python environments
scanPythonEnvironments();
// 檢測系統信息 / Detect system information
detectSystemInfo();
// 延遲載入保存的設定,確保 UI 完全初始化 / Delay loading saved settings to ensure UI is fully initialized
QTimer::singleShot(100, this, [this]() {
if (hasSavedSettings()) {
loadSettings();
// 在應用設定前,先確保虛擬環境列表已更新 / Ensure virtual environments list is updated before applying settings
if (!currentPythonPath.isEmpty()) {
scanVirtualEnvironments(currentPythonPath);
}
applySavedSettings();
} else {
// 如果沒有保存的設定,提醒用戶 / If no saved settings, remind user
QMessageBox::information(this,
tr("歡迎使用 Capybara / Welcome to Capybara"),
tr("請選擇一個 Python 環境並點擊「指定此環境」按鈕來保存設定。\n"
"Please select a Python environment and click \"指定此環境\" button to save settings."));
}
});
// 初始化數據處理模塊 / Initialize data processing module
imageProcessor = nullptr;
processingPipeline = nullptr;
setupDataProcessingTab();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::scanPythonEnvironments()
{
pythonEnvironments.clear();
ui->pythonComboBox->clear();
detectPythonEnvironments();
updateComboBox();
if (pythonEnvironments.isEmpty()) {
ui->pythonComboBox->addItem("未找到 Python 環境");
ui->pythonPathLabel->setText("路徑:未找到");
currentPythonPath.clear();
virtualEnvironments.clear();
ui->venvComboBox->clear();
ui->venvComboBox->setEnabled(false);
ui->venvPathLabel->setText("虛擬環境路徑:未找到");
} else {
ui->pythonPathLabel->setText("路徑:" + pythonEnvironments[0].path);
currentPythonPath = pythonEnvironments[0].path;
// 掃描第一個 Python 環境的虛擬環境 / Scan virtual environments for first Python environment
scanVirtualEnvironments(pythonEnvironments[0].path);
}
}
void MainWindow::detectPythonEnvironments()
{
QStringList pythonPaths;
// 方法 1: 從 PATH 環境變數中查找 / Method 1: Find from PATH environment variable
pythonPaths.append(findPythonInPath());
// 方法 2: 使用 Python Launcher (py.exe) 查找 / Method 2: Find using Python Launcher (py.exe)
pythonPaths.append(findPythonViaLauncher());
// 方法 3: 檢查常見安裝位置 / Method 3: Check common installation locations
pythonPaths.append(findPythonInCommonLocations());
// 去重並驗證每個 Python 路徑 / Remove duplicates and validate each Python path
QStringList uniquePaths;
for (const QString &path : pythonPaths) {
if (!uniquePaths.contains(path) && QFileInfo::exists(path)) {
QString version = getPythonVersion(path);
if (!version.isEmpty()) {
PythonEnvironment env;
env.path = path;
env.version = version;
env.displayName = QString("Python %1 - %2").arg(version, path);
pythonEnvironments.append(env);
uniquePaths.append(path);
}
}
}
}
QStringList MainWindow::findPythonInPath()
{
QStringList results;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString pathEnv = env.value("PATH");
QStringList paths = pathEnv.split(QDir::listSeparator());
for (const QString &dir : paths) {
QString pythonPath = QDir(dir).absoluteFilePath("python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
return results;
}
QStringList MainWindow::findPythonViaLauncher()
{
QStringList results;
// 使用 py.exe -0 列出所有已安裝的 Python / Use py.exe -0 to list all installed Python versions
QProcess process;
process.start("py.exe", QStringList() << "-0");
process.waitForFinished(3000);
if (process.exitCode() == 0) {
QString output = QString::fromUtf8(process.readAllStandardOutput());
QStringList lines = output.split('\n', Qt::SkipEmptyParts);
for (const QString &line : lines) {
// 解析 py.exe -0 的輸出格式 / Parse py.exe -0 output format
// 例如: " -3.11-64 * C:\Python311\python.exe" / Example: " -3.11-64 * C:\Python311\python.exe"
QString trimmed = line.trimmed();
if (trimmed.contains("python.exe")) {
// 提取路徑 / Extract path
int exeIndex = trimmed.indexOf("python.exe");
if (exeIndex > 0) {
QString path = trimmed.mid(exeIndex - 1).trimmed();
if (QFileInfo::exists(path)) {
results.append(path);
}
}
}
}
}
return results;
}
QStringList MainWindow::findPythonInCommonLocations()
{
QStringList results;
// Windows 常見 Python 安裝位置 / Windows common Python installation locations
QStringList commonPaths = {
"C:\\Python*\\python.exe",
QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/AppData/Local/Programs/Python/*/python.exe",
"C:\\Program Files\\Python*\\python.exe",
"C:\\Program Files (x86)\\Python*\\python.exe",
};
// 檢查特定版本目錄 / Check version-specific directories
QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
QDir pythonDir(homeDir + "/AppData/Local/Programs/Python");
if (pythonDir.exists()) {
QStringList entries = pythonDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
QString pythonPath = pythonDir.absoluteFilePath(entry + "/python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
}
// 檢查系統 Program Files / Check system Program Files
QDir programFiles("C:/Program Files");
if (programFiles.exists()) {
QStringList entries = programFiles.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
if (entry.startsWith("Python")) {
QString pythonPath = programFiles.absoluteFilePath(entry + "/python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
}
}
// 檢查 Program Files (x86) / Check Program Files (x86)
QDir programFilesX86("C:/Program Files (x86)");
if (programFilesX86.exists()) {
QStringList entries = programFilesX86.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
if (entry.startsWith("Python")) {
QString pythonPath = programFilesX86.absoluteFilePath(entry + "/python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
}
}
// 檢查虛擬環境(常見位置) / Check virtual environments (common locations)
QStringList venvPaths = {
homeDir + "/.virtualenvs",
homeDir + "/venv",
homeDir + "/env",
};
for (const QString &venvBase : venvPaths) {
QDir venvDir(venvBase);
if (venvDir.exists()) {
// 查找直接子目錄中的虛擬環境 / Find virtual environments in direct subdirectories
QStringList entries = venvDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
QString pythonPath = venvDir.absoluteFilePath(entry + "/Scripts/python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
}
}
// 檢查當前目錄下的虛擬環境 / Check virtual environments in current directory
QDir currentDir(QDir::current());
QStringList currentVenvDirs = {"venv", "env", ".venv"};
for (const QString &venvDir : currentVenvDirs) {
QString pythonPath = currentDir.absoluteFilePath(venvDir + "/Scripts/python.exe");
if (QFileInfo::exists(pythonPath)) {
results.append(pythonPath);
}
}
return results;
}
QString MainWindow::getPythonVersion(const QString &pythonPath)
{
QProcess process;
process.start(pythonPath, QStringList() << "--version");
process.waitForFinished(3000);
if (process.exitCode() == 0) {
QString output = QString::fromUtf8(process.readAllStandardOutput());
// 輸出格式通常是 "Python 3.11.0" 或 "Python 3.11.0\n" / Output format is usually "Python 3.11.0" or "Python 3.11.0\n"
output = output.trimmed();
if (output.startsWith("Python ")) {
return output.mid(7).trimmed(); // 移除 "Python " 前綴 / Remove "Python " prefix
}
}
return QString();
}
void MainWindow::updateComboBox()
{
ui->pythonComboBox->clear();
for (const PythonEnvironment &env : pythonEnvironments) {
ui->pythonComboBox->addItem(env.displayName);
}
}
void MainWindow::onPythonComboBoxChanged(int index)
{
if (index >= 0 && index < pythonEnvironments.size()) {
const PythonEnvironment &env = pythonEnvironments[index];
ui->pythonPathLabel->setText("路徑:" + env.path);
currentPythonPath = env.path;
// 掃描該 Python 環境的虛擬環境 / Scan virtual environments for this Python
scanVirtualEnvironments(env.path);
// 清除之前的選擇和檢測結果 / Clear previous selection and detection results
selectedEnvName.clear();
selectedEnvPath.clear();
selectedPythonPath.clear();
ui->selectedEnvLabel->setText("已指定環境:無");
ui->selectEnvButton->setEnabled(false);
ui->pythonPackagesLabel->setText("Python 套件:請選擇虛擬環境並點擊「指定此環境」");
ui->pytorchInfoLabel->setText("PyTorch:未檢測");
ui->ultralyticsInfoLabel->setText("Ultralytics:未檢測");
} else {
ui->pythonPathLabel->setText("路徑:未選擇");
currentPythonPath.clear();
virtualEnvironments.clear();
ui->venvComboBox->clear();
ui->venvComboBox->setEnabled(false);
ui->venvPathLabel->setText("虛擬環境路徑:未選擇");
// 清除 Python 套件信息 / Clear Python package information
ui->pythonPackagesLabel->setText("Python 套件:未選擇環境");
ui->pytorchInfoLabel->setText("PyTorch:未檢測");
ui->ultralyticsInfoLabel->setText("Ultralytics:未檢測");
}
}
void MainWindow::onRefreshButtonClicked()
{
scanPythonEnvironments();
// 如果已選擇 Python 環境,重新掃描虛擬環境 / If Python environment is selected, rescan virtual environments
if (!currentPythonPath.isEmpty()) {
scanVirtualEnvironments(currentPythonPath);
}
QMessageBox::information(this, "掃描完成",
QString("找到 %1 個 Python 環境,%2 個虛擬環境")
.arg(pythonEnvironments.size())
.arg(virtualEnvironments.size()));
}
void MainWindow::scanVirtualEnvironments(const QString &pythonPath)
{
virtualEnvironments.clear();
ui->venvComboBox->clear();
QStringList venvPaths = findVirtualEnvironments(pythonPath);
// 添加 conda 環境 / Add conda environments
QMap<QString, QString> condaEnvs = findCondaEnvironments(); // 名稱到路徑的映射 / Name to path mapping
for (const QString &condaEnvPath : condaEnvs.values()) {
if (!venvPaths.contains(condaEnvPath)) {
venvPaths.append(condaEnvPath);
}
}
// 驗證每個虛擬環境是否屬於選定的 Python 或是 conda 環境 / Validate each virtual environment belongs to selected Python or is a conda environment
for (const QString &venvPath : venvPaths) {
bool isValid = false;
QString envName;
// 檢查是否為 conda 環境 / Check if it's a conda environment
if (isCondaEnvironment(venvPath)) {
isValid = true;
// 從映射中獲取 conda 環境名稱 / Get conda environment name from map
QString condaName = condaEnvs.key(venvPath, "");
if (!condaName.isEmpty()) {
envName = condaName; // 使用 conda 的實際環境名稱 / Use actual conda environment name
} else {
// 如果找不到名稱,使用目錄名 / If name not found, use directory name
QFileInfo venvInfo(venvPath);
envName = venvInfo.dir().dirName();
}
} else if (isVirtualEnvironmentForPython(venvPath, pythonPath)) {
isValid = true;
// 獲取虛擬環境名稱(目錄名) / Get virtual environment name (directory name)
QFileInfo venvInfo(venvPath);
envName = venvInfo.dir().dirName();
}
if (isValid) {
VirtualEnvironment venv;
venv.path = venvPath;
venv.pythonPath = pythonPath;
// 設置環境名稱 / Set environment name
if (isCondaEnvironment(venvPath)) {
venv.name = "[Conda] " + envName; // 使用 conda 的實際環境名稱 / Use actual conda environment name
} else {
venv.name = envName;
}
// 獲取虛擬環境中的 Python 路徑 / Get Python path in virtual environment
QString venvPython = getVenvPythonPath(venvPath);
if (!venvPython.isEmpty()) {
venv.displayName = QString("%1 (%2)").arg(venv.name, venvPython);
} else {
venv.displayName = venv.name;
}
virtualEnvironments.append(venv);
}
}
updateVenvComboBox();
}
QStringList MainWindow::findVirtualEnvironments(const QString &pythonPath)
{
QStringList results;
QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
// 常見虛擬環境位置 / Common virtual environment locations
QStringList searchPaths = {
homeDir + "/.virtualenvs",
homeDir + "/venv",
homeDir + "/env",
homeDir + "/Envs",
QDir::current().absolutePath() + "/venv",
QDir::current().absolutePath() + "/env",
QDir::current().absolutePath() + "/.venv",
};
// 檢查 Python 安裝目錄的父目錄 / Check parent directory of Python installation
QFileInfo pythonInfo(pythonPath);
QDir pythonParentDir = pythonInfo.dir();
pythonParentDir.cdUp();
searchPaths.append(pythonParentDir.absolutePath() + "/venv");
searchPaths.append(pythonParentDir.absolutePath() + "/env");
// 遞歸查找所有包含 pyvenv.cfg 的目錄 / Recursively find all directories containing pyvenv.cfg
for (const QString &basePath : searchPaths) {
QDir baseDir(basePath);
if (baseDir.exists()) {
// 檢查直接子目錄 / Check direct subdirectories
QStringList entries = baseDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
QString venvPath = baseDir.absoluteFilePath(entry);
QString pyvenvCfg = QDir(venvPath).absoluteFilePath("pyvenv.cfg");
if (QFileInfo::exists(pyvenvCfg)) {
results.append(venvPath);
}
}
// 也檢查當前目錄本身是否為虛擬環境 / Also check if current directory itself is a virtual environment
QString pyvenvCfg = baseDir.absoluteFilePath("pyvenv.cfg");
if (QFileInfo::exists(pyvenvCfg)) {
results.append(basePath);
}
}
}
// 使用 Python 的 site-packages 位置來查找可能的虛擬環境 / Use Python's site-packages location to find possible virtual environments
QProcess process;
process.start(pythonPath, QStringList() << "-c" << "import sys; print(sys.prefix)");
process.waitForFinished(3000);
if (process.exitCode() == 0) {
QString pythonPrefix = QString::fromUtf8(process.readAllStandardOutput()).trimmed();
QDir pythonPrefixDir(pythonPrefix);
if (pythonPrefixDir.exists()) {
// 檢查父目錄中的虛擬環境 / Check virtual environments in parent directory
pythonPrefixDir.cdUp();
QStringList entries = pythonPrefixDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
QString venvPath = pythonPrefixDir.absoluteFilePath(entry);
QString pyvenvCfg = QDir(venvPath).absoluteFilePath("pyvenv.cfg");
if (QFileInfo::exists(pyvenvCfg)) {
results.append(venvPath);
}
}
}
}
return results;
}
QMap<QString, QString> MainWindow::findCondaEnvironments()
{
QMap<QString, QString> results; // 環境名稱 -> 路徑映射 / Environment name -> path mapping
// 嘗試使用 conda info -e 命令 / Try using conda info -e command
QProcess process;
// 首先嘗試直接執行 conda / First try executing conda directly
process.start("conda", QStringList() << "info" << "-e");
process.waitForFinished(5000);
// 如果失敗,嘗試使用 conda.exe / If failed, try conda.exe
if (process.exitCode() != 0) {
process.start("conda.exe", QStringList() << "info" << "-e");
process.waitForFinished(5000);
}
// 如果還是失敗,嘗試 conda env list / If still failed, try conda env list
if (process.exitCode() != 0) {
process.start("conda", QStringList() << "env" << "list");
process.waitForFinished(5000);
}
if (process.exitCode() == 0) {
QString output = QString::fromUtf8(process.readAllStandardOutput());
QStringList lines = output.split('\n', Qt::SkipEmptyParts);
// 解析 conda 輸出 / Parse conda output
// 格式通常是: # conda environments: 或環境列表 / Format is usually: # conda environments: or environment list
// 例如: base C:\Users\...\anaconda3 / Example: base C:\Users\...\anaconda3
// 或者: base * C:\Users\...\anaconda3 / Or: base * C:\Users\...\anaconda3
bool inEnvironmentList = false;
for (const QString &line : lines) {
QString trimmed = line.trimmed();
// 跳過空行 / Skip empty lines
if (trimmed.isEmpty()) {
continue;
}
// 檢查是否為標題行 / Check if it's a header line
if (trimmed.startsWith("#")) {
if (trimmed.contains("conda environments", Qt::CaseInsensitive) ||
trimmed.contains("environment", Qt::CaseInsensitive)) {
inEnvironmentList = true;
}
continue;
}
// 如果已經進入環境列表部分,解析環境路徑 / If in environment list section, parse environment paths
if (inEnvironmentList || (!trimmed.startsWith("#") && trimmed.contains(QRegularExpression("^[a-zA-Z0-9_\\-]+")))) {
// 分割環境名稱和路徑 / Split environment name and path
// 格式: 環境名稱 + 多個空格 + 可選的 * + 路徑 / Format: env name + multiple spaces + optional * + path
// 例如: base C:\Users\...\anaconda3 / Example: base C:\Users\...\anaconda3
// 或者: base * C:\Users\...\anaconda3 / Or: base * C:\Users\...\anaconda3
QString envName;
QString envPath;
// 使用正則表達式匹配:環境名 + 一個或多個空格 + 可選的 * + 一個或多個空格 + 路徑 / Use regex to match: env name + one or more spaces + optional * + one or more spaces + path
QRegularExpression re("^([a-zA-Z0-9_\\-]+)\\s+\\*?\\s*(.+)$");
QRegularExpressionMatch match = re.match(trimmed);
if (match.hasMatch()) {
// 匹配成功,提取名稱和路徑 / Match successful, extract name and path
envName = match.captured(1).trimmed();
envPath = match.captured(2).trimmed();
} else {
// 如果正則匹配失敗,使用空格分割 / If regex match fails, split by spaces
QStringList parts = trimmed.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
if (parts.size() >= 2) {
// 第一個部分是環境名稱,最後一個部分是路徑 / First part is environment name, last part is path
envName = parts.first();
envPath = parts.last();
} else if (parts.size() == 1) {
// 只有一個部分,可能是路徑 / Only one part, might be a path
envPath = parts[0];
// 從路徑提取名稱 / Extract name from path
QFileInfo pathInfo(envPath);
QString dirName = pathInfo.dir().dirName();
// 如果是 envs 目錄,使用父目錄名 / If it's in envs directory, use parent directory name
if (dirName == "envs") {
envName = pathInfo.baseName();
} else {
envName = dirName;
}
}
}
// 驗證路徑 / Validate path
if (!envPath.isEmpty()) {
QDir envDir(envPath);
if (envDir.exists()) {
// 檢查是否為 conda 環境(包含 conda-meta 目錄) / Check if it's a conda environment (contains conda-meta directory)
QString condaMeta = envDir.absoluteFilePath("conda-meta");
if (QFileInfo::exists(condaMeta)) {
// 如果沒有名稱,使用目錄名 / If no name, use directory name
if (envName.isEmpty()) {
QFileInfo pathInfo(envPath);
envName = pathInfo.dir().dirName();
}
results.insert(envName, envPath); // 存儲名稱和路徑的映射 / Store name and path mapping
}
}
}
}
}
}
// 如果命令執行失敗,嘗試查找常見的 conda 安裝位置 / If command execution failed, try finding common conda installation locations
if (results.isEmpty()) {
QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
QStringList condaPaths = {
homeDir + "/anaconda3",
homeDir + "/miniconda3",
homeDir + "/anaconda",
homeDir + "/miniconda",
"C:/ProgramData/Anaconda3",
"C:/ProgramData/Miniconda3",
"C:/Users/Public/anaconda3",
"C:/Users/Public/miniconda3",
};
// 檢查 conda 環境目錄 / Check conda environments directory
for (const QString &condaBase : condaPaths) {
QDir condaDir(condaBase);
if (condaDir.exists()) {
// 檢查 envs 目錄 / Check envs directory
QDir envsDir(condaDir.absoluteFilePath("envs"));
if (envsDir.exists()) {
QStringList envDirs = envsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &envName : envDirs) {
QString envPath = envsDir.absoluteFilePath(envName);
QString condaMeta = QDir(envPath).absoluteFilePath("conda-meta");
if (QFileInfo::exists(condaMeta)) {
results.insert(envName, envPath); // 使用目錄名作為環境名稱 / Use directory name as environment name
}
}
}
// base 環境本身 / Base environment itself
QString condaMeta = condaDir.absoluteFilePath("conda-meta");
if (QFileInfo::exists(condaMeta)) {
// base 環境名稱固定為 "base" / Base environment name is always "base"
results.insert("base", condaBase);
}
}
}
}
return results;
}
bool MainWindow::isCondaEnvironment(const QString &venvPath)
{
// 檢查是否包含 conda-meta 目錄 / Check if it contains conda-meta directory
QDir venvDir(venvPath);
QString condaMeta = venvDir.absoluteFilePath("conda-meta");
return QFileInfo::exists(condaMeta);
}
bool MainWindow::isVirtualEnvironmentForPython(const QString &venvPath, const QString &pythonPath)
{
// 讀取 pyvenv.cfg 文件 / Read pyvenv.cfg file
QString pyvenvCfgPath = QDir(venvPath).absoluteFilePath("pyvenv.cfg");
QFile pyvenvCfg(pyvenvCfgPath);
if (!pyvenvCfg.open(QIODevice::ReadOnly | QIODevice::Text)) {
return false;
}
QTextStream in(&pyvenvCfg);
QString basePython;
// 解析配置文件,查找 base-python 或 home / Parse config file, find base-python or home
while (!in.atEnd()) {
QString line = in.readLine().trimmed();
if (line.startsWith("base-python") || line.startsWith("home")) {
QStringList parts = line.split("=");
if (parts.size() >= 2) {
basePython = parts[1].trimmed();
break;
}
}
}
pyvenvCfg.close();
// 標準化路徑進行比較 / Normalize paths for comparison
QFileInfo pythonInfo(pythonPath);
QString normalizedPythonPath = QDir::toNativeSeparators(pythonInfo.absoluteFilePath());
if (!basePython.isEmpty()) {
QString normalizedBasePython = QDir::toNativeSeparators(QFileInfo(basePython).absoluteFilePath());
// 比較路徑(不區分大小寫,因為 Windows) / Compare paths (case-insensitive for Windows)
return normalizedBasePython.compare(normalizedPythonPath, Qt::CaseInsensitive) == 0;
}
return false;
}
QString MainWindow::getVenvPythonPath(const QString &venvPath)
{
qDebug() << "\n=== 查找 Python 路徑 ===";
qDebug() << "虛擬環境路徑:" << venvPath;
// 檢查是否為 Conda 環境 / Check if it's a Conda environment
bool isConda = isCondaEnvironment(venvPath);
qDebug() << "是否為 Conda 環境:" << isConda;
// Conda 環境的 Python 路徑檢查順序 / Conda environment Python path check order
QStringList condaPaths = {
QDir(venvPath).absoluteFilePath("python.exe"), // Windows 根目錄 / Windows root
QDir(venvPath).absoluteFilePath("bin/python.exe"), // Windows bin 目錄 / Windows bin directory
QDir(venvPath).absoluteFilePath("bin/python"), // Unix bin 目錄 / Unix bin directory
};
// 標準虛擬環境的 Python 路徑檢查順序 / Standard virtual environment Python path check order
QStringList standardPaths = {
QDir(venvPath).absoluteFilePath("Scripts/python.exe"), // Windows Scripts / Windows Scripts
QDir(venvPath).absoluteFilePath("bin/python.exe"), // Windows bin / Windows bin
QDir(venvPath).absoluteFilePath("bin/python"), // Unix bin / Unix bin
};
// 優先檢查 Conda 環境路徑 / Check Conda paths first if it's a Conda environment
QStringList pathsToCheck = isConda ? condaPaths : standardPaths;
for (const QString &path : pathsToCheck) {
qDebug() << "檢查路徑:" << path;
if (QFileInfo::exists(path)) {
qDebug() << "找到 Python:" << path;
return path;
}
}
// 如果都沒找到,也檢查標準路徑 / If not found, also check standard paths
if (isConda) {
for (const QString &path : standardPaths) {
qDebug() << "檢查標準路徑:" << path;
if (QFileInfo::exists(path)) {
qDebug() << "找到 Python (標準路徑):" << path;
return path;
}
}
}
qDebug() << "未找到 Python 可執行文件";
return QString();
}
void MainWindow::updateVenvComboBox()
{
ui->venvComboBox->clear();
if (virtualEnvironments.isEmpty()) {
ui->venvComboBox->addItem("未找到虛擬環境");
ui->venvComboBox->setEnabled(false);
ui->venvPathLabel->setText("虛擬環境路徑:未找到");
ui->selectEnvButton->setEnabled(false);
} else {
ui->venvComboBox->setEnabled(true);
for (const VirtualEnvironment &venv : virtualEnvironments) {
ui->venvComboBox->addItem(venv.displayName);
}
// 優先選擇保存的虛擬環境,如果沒有則選擇第一個 / Prefer saved virtual environment, otherwise select first
int selectedIndex = 0;
QString displayPath;
// 檢查是否有保存的虛擬環境路徑 / Check if there's a saved virtual environment path
if (!selectedEnvPath.isEmpty()) {
// 查找保存的虛擬環境在列表中的位置 / Find saved virtual environment in the list
for (int i = 0; i < virtualEnvironments.size(); ++i) {
if (virtualEnvironments[i].path == selectedEnvPath) {
selectedIndex = i;
displayPath = selectedEnvPath; // 使用保存的路徑 / Use saved path
break;
}
}
}
// 如果沒有找到保存的環境,使用第一個 / If saved environment not found, use first
if (displayPath.isEmpty() && !virtualEnvironments.isEmpty()) {
selectedIndex = 0;
displayPath = virtualEnvironments[0].path;
}
// 暫時阻止信號發射,避免觸發 onVenvComboBoxChanged / Block signals temporarily to avoid triggering onVenvComboBoxChanged
ui->venvComboBox->blockSignals(true);
ui->venvComboBox->setCurrentIndex(selectedIndex);
ui->venvComboBox->blockSignals(false);
// 顯示虛擬環境路徑 / Display virtual environment path
ui->venvPathLabel->setText("虛擬環境路徑:" + displayPath);
ui->selectEnvButton->setEnabled(true);
}
}
void MainWindow::onVenvComboBoxChanged(int index)
{
if (index >= 0 && index < virtualEnvironments.size()) {
const VirtualEnvironment &venv = virtualEnvironments[index];
ui->venvPathLabel->setText("虛擬環境路徑:" + venv.path);
// 啟用"指定此環境"按鈕 / Enable "Select Environment" button
ui->selectEnvButton->setEnabled(true);
// 清除之前的檢測結果 / Clear previous detection results
ui->pythonPackagesLabel->setText("Python 套件:請點擊「指定此環境」按鈕開始檢測");
ui->pytorchInfoLabel->setText("PyTorch:未檢測");
ui->ultralyticsInfoLabel->setText("Ultralytics:未檢測");
} else {
ui->venvPathLabel->setText("虛擬環境路徑:未選擇");
ui->selectEnvButton->setEnabled(false);
ui->pythonPackagesLabel->setText("Python 套件:請選擇環境");
ui->pytorchInfoLabel->setText("PyTorch:未檢測");
ui->ultralyticsInfoLabel->setText("Ultralytics:未檢測");
}
}
void MainWindow::onSelectEnvButtonClicked()
{
int index = ui->venvComboBox->currentIndex();
if (index >= 0 && index < virtualEnvironments.size()) {
const VirtualEnvironment &venv = virtualEnvironments[index];
// 保存選擇的環境信息 / Save selected environment information
selectedEnvName = venv.name;
selectedEnvPath = venv.path;
// 移除 [Conda] 前綴用於顯示 / Remove [Conda] prefix for display
QString displayName = selectedEnvName;
if (displayName.startsWith("[Conda] ")) {
displayName = displayName.mid(8);
}
// 更新已指定環境標籤 / Update selected environment label
ui->selectedEnvLabel->setText(QString("已指定環境:%1").arg(displayName));
// 獲取虛擬環境中的 Python 路徑 / Get Python path in virtual environment
QString venvPython = getVenvPythonPath(venv.path);
selectedPythonPath = venvPython;
// 保存設定 / Save settings
saveSettings();
// 調試:顯示 Python 路徑 / Debug: display Python path
qDebug() << "=== 開始檢測環境 ===";
qDebug() << "環境名稱:" << displayName;
qDebug() << "環境路徑:" << venv.path;
qDebug() << "獲取的 Python 路徑:" << venvPython;
qDebug() << "Python 路徑是否存在:" << QFileInfo::exists(venvPython);
// 如果獲取的路徑為空,嘗試其他方法 / If path is empty, try other methods
if (venvPython.isEmpty()) {
// 嘗試直接使用環境路徑下的 python.exe / Try python.exe directly in environment path
QString directPython = QDir(venv.path).absoluteFilePath("python.exe");
if (QFileInfo::exists(directPython)) {
venvPython = directPython;
qDebug() << "使用直接路徑:" << venvPython;
}
}
if (!venvPython.isEmpty() && QFileInfo::exists(venvPython)) {
// 測試 Python 是否可用 / Test if Python is usable
QProcess testProcess;
// 設置環境變數,清除可能干擾的 PYTHONHOME / Set environment variables, clear interfering PYTHONHOME
QProcessEnvironment testEnv = QProcessEnvironment::systemEnvironment();
testEnv.remove("PYTHONHOME"); // 清除 PYTHONHOME / Clear PYTHONHOME
testEnv.remove("PYTHONPATH"); // 清除 PYTHONPATH / Clear PYTHONPATH
testProcess.setProcessEnvironment(testEnv);
testProcess.start(venvPython, QStringList() << "--version");
testProcess.waitForFinished(3000);
if (testProcess.exitCode() == 0) {
QString pythonVersion = QString::fromUtf8(testProcess.readAllStandardOutput()).trimmed();
qDebug() << "Python 版本測試成功:" << pythonVersion;
} else {
QString errorOutput = QString::fromUtf8(testProcess.readAllStandardError());
qDebug() << "Python 版本測試失敗,退出碼:" << testProcess.exitCode();
qDebug() << "錯誤輸出:" << errorOutput;
}
// 再次判斷是否為 Conda 環境 / Check again if it's a Conda environment
bool isConda = isCondaEnvironment(venv.path);
bool isPythonConda = isPythonFromConda(venvPython);
// 顯示選擇的環境名稱和開始檢測 / Display selected environment name and start detection
if (isConda || isPythonConda) {
ui->pythonPackagesLabel->setText(QString("Python 套件:%1 (Conda 環境) - 檢測中...").arg(displayName));
} else {
ui->pythonPackagesLabel->setText(QString("Python 套件:%1 - 檢測中...").arg(displayName));
}
// 立即更新 UI,然後開始檢測 / Update UI immediately, then start detection
QApplication::processEvents();
// 開始檢測 Python 套件 / Start detecting Python packages
detectPythonPackages(venvPython);
} else {
QString errorMsg = venvPython.isEmpty() ? "無法找到 Python 可執行文件" : QString("Python 路徑不存在:%1").arg(venvPython);
ui->pythonPackagesLabel->setText(QString("Python 套件:%1 - %2").arg(displayName, errorMsg));
ui->pytorchInfoLabel->setText("PyTorch:未檢測");
ui->ultralyticsInfoLabel->setText("Ultralytics:未檢測");
}
}
}
// 系統檢測方法實現 / System detection method implementations
void MainWindow::detectSystemInfo()
{
QString arch = detectSystemArchitecture();
QString cuda = detectCUDA();
QString gpu = detectGPU();
ui->systemInfoLabel->setText(QString("系統架構:%1").arg(arch));
ui->cudaInfoLabel->setText(QString("CUDA:%1").arg(cuda));
ui->gpuInfoLabel->setText(QString("GPU:%1").arg(gpu));
}
QString MainWindow::detectSystemArchitecture()
{
// 檢測系統架構 / Detect system architecture
#ifdef Q_PROCESSOR_X86_64
return "x64 (64-bit)";
#elif defined(Q_PROCESSOR_X86_32)
return "x86 (32-bit)";
#elif defined(Q_PROCESSOR_ARM_64)
return "ARM64";
#elif defined(Q_PROCESSOR_ARM)
return "ARM";
#else
return "未知 / Unknown";
#endif
}
QString MainWindow::detectCUDA()
{
QStringList cudaPaths = {
"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA",
"C:/Program Files (x86)/NVIDIA GPU Computing Toolkit/CUDA",
};
// 查找 CUDA 安裝目錄 / Find CUDA installation directory
QStringList cudaVersions;
for (const QString &basePath : cudaPaths) {
QDir cudaDir(basePath);
if (cudaDir.exists()) {
QStringList entries = cudaDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
// 檢查是否為版本目錄(例如 v11.8, v12.0) / Check if it's a version directory
QRegularExpression versionRe("^v?\\d+\\.\\d+");
if (versionRe.match(entry).hasMatch()) {
QString version = entry;
if (version.startsWith("v")) {
version = version.mid(1);
}
cudaVersions.append(version);
}
}
}
}
// 使用 nvidia-smi 檢測 CUDA 版本 / Use nvidia-smi to detect CUDA version
QProcess process;
process.start("nvidia-smi", QStringList() << "--query-gpu=driver_version,cuda_version" << "--format=csv,noheader");
process.waitForFinished(3000);
if (process.exitCode() == 0) {
QString output = QString::fromUtf8(process.readAllStandardOutput()).trimmed();
if (!output.isEmpty()) {
QStringList parts = output.split(',');
if (parts.size() >= 2) {
QString cudaVersion = parts[1].trimmed();
if (!cudaVersion.isEmpty() && cudaVersion != "Not Supported") {
return QString("已安裝 (驅動版本: %1, CUDA: %2)").arg(parts[0].trimmed(), cudaVersion);