-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.js
More file actions
2027 lines (1779 loc) · 81.4 KB
/
main.js
File metadata and controls
2027 lines (1779 loc) · 81.4 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
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
let autoUpdater = null;
try {
({ autoUpdater } = require('electron-updater'));
} catch (error) {
console.log('[Auto-Updater] electron-updater not available:', error.message);
}
const path = require('path');
const fs = require('fs');
const { spawn, execSync } = require('child_process');
const os = require('os');
const axios = require('axios');
const EnhancedSubtitleTranslator = require('./translator-enhanced');
const { Menu } = require('electron');
// ffmpeg-static: npm 패키지에서 자동으로 플랫폼별 ffmpeg 바이너리 제공
let ffmpegStaticPath = null;
try {
ffmpegStaticPath = require('ffmpeg-static');
if (ffmpegStaticPath && ffmpegStaticPath.includes('app.asar')) {
ffmpegStaticPath = ffmpegStaticPath.replace('app.asar', 'app.asar.unpacked');
}
console.log('[FFmpeg] Using ffmpeg-static:', ffmpegStaticPath);
} catch (_error) {
console.log('[FFmpeg] ffmpeg-static not available, will use system PATH or local binary');
}
// ffprobe-static: npm 패키지에서 자동으로 플랫폼별 ffprobe 바이너리 제공
let ffprobeStaticPath = null;
try {
ffprobeStaticPath = require('ffprobe-static').path;
if (ffprobeStaticPath && ffprobeStaticPath.includes('app.asar')) {
ffprobeStaticPath = ffprobeStaticPath.replace('app.asar', 'app.asar.unpacked');
}
console.log('[FFprobe] Using ffprobe-static:', ffprobeStaticPath);
} catch (_error) {
console.log('[FFprobe] ffprobe-static not available, will use system PATH or local binary');
}
// Allow autoplay of audio (오디오 자동재생 허용)
try {
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
} catch (error) {
console.log('[Audio] Failed to set autoplay policy:', error.message);
}
// Global variables
let mainWindow;
let currentProcess = null;
let isUserStopped = false;
let translator = new EnhancedSubtitleTranslator();
// ===== Download cancellation state (모델 다운로드 취소 관리) =====
let activeDownloads = new Set(); // { controller, writer, destPath }
let downloadsCancelled = false;
function cancelActiveDownloads() {
downloadsCancelled = true;
for (const d of activeDownloads) {
try {
d.controller?.abort();
} catch (error) {
console.log('[Download] Controller abort failed:', error.message);
}
try {
d.writer?.destroy?.();
} catch (error) {
console.log('[Download] Writer destroy failed:', error.message);
}
}
activeDownloads.clear();
try {
mainWindow?.webContents?.send('output-update', 'Model download cancelled\n');
} catch (error) {
console.log('[Download] Failed to send cancellation message:', error.message);
}
}
// ===== Device auto-selection helper (장치 자동 선택 헬퍼) =====
// Platform-specific whisper-cli binary name
const WHISPER_CLI_NAME = process.platform === 'win32' ? 'whisper-cli.exe' : 'whisper-cli';
// CUDA 12 requires compute capability >= 5.0 (Maxwell+)
const CUDA12_MIN_COMPUTE = 5.0;
let _gpuInfoCache = null;
let _gpuWarningShown = false;
function getGpuInfo() {
if (_gpuInfoCache !== null) return _gpuInfoCache;
try {
const raw = execSync('nvidia-smi --query-gpu=name,compute_cap --format=csv,noheader', {
encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore']
}).trim();
if (!raw) { _gpuInfoCache = { available: false }; return _gpuInfoCache; }
const firstLine = raw.split('\n')[0];
const parts = firstLine.split(',').map(s => s.trim());
const gpuName = parts[0] || 'Unknown GPU';
const computeCap = parseFloat(parts[1]) || 0;
_gpuInfoCache = {
available: true,
name: gpuName,
computeCap,
cudaCompatible: computeCap >= CUDA12_MIN_COMPUTE
};
console.log(`[GPU Info] ${gpuName}, Compute Capability: ${computeCap}, CUDA 12 compatible: ${computeCap >= CUDA12_MIN_COMPUTE}`);
} catch {
try {
// 상세 쿼리 실패 시 nvidia-smi -L로 GPU 존재만 확인
// compute_cap을 알 수 없으므로 안전하게 CPU 사용 (구형 GPU에서 CUDA 12 크래시 방지)
execSync('nvidia-smi -L', { stdio: 'ignore', timeout: 2000 });
_gpuInfoCache = { available: true, name: 'Unknown NVIDIA GPU', computeCap: 0, cudaCompatible: false };
} catch {
_gpuInfoCache = { available: false };
}
}
return _gpuInfoCache;
}
function isCudaAvailable() {
const info = getGpuInfo();
return info.available && info.cudaCompatible;
}
// ===== CUDA Library Path Helper (Linux LD_LIBRARY_PATH) =====
// On Linux, CUDA-built whisper-cli needs LD_LIBRARY_PATH to find .so files.
// Electron apps launched from desktop may not inherit shell env vars.
let _cudaLibPathCache = null;
function getCudaLibraryPaths() {
if (_cudaLibPathCache !== null) return _cudaLibPathCache;
if (process.platform === 'win32') { _cudaLibPathCache = []; return []; }
const found = [];
const candidates = [
'/usr/local/cuda/lib64',
'/usr/local/cuda/lib',
'/usr/lib/wsl/lib', // WSL2 CUDA library path
'/usr/lib/x86_64-linux-gnu',
'/usr/lib64',
];
// Detect versioned CUDA installations (e.g. /usr/local/cuda-13.2/lib64)
try {
const localDirs = fs.readdirSync('/usr/local');
for (const dir of localDirs) {
if (dir.startsWith('cuda-')) {
candidates.push(`/usr/local/${dir}/lib64`);
candidates.push(`/usr/local/${dir}/lib`);
}
}
} catch (_e) { /* ignore */ }
for (const p of candidates) {
try { if (fs.existsSync(p)) found.push(p); } catch (_e) { /* ignore */ }
}
_cudaLibPathCache = found;
if (found.length > 0) {
console.log('[CUDA Libs] Found library paths:', found.join(', '));
}
return found;
}
function getWhisperSpawnEnv(device, whisperDir) {
// On Windows, no env override needed
if (process.platform === 'win32') return undefined;
const cudaPaths = device === 'cuda' ? getCudaLibraryPaths() : [];
const allPaths = [];
// Always include whisper-cpp dir itself (for libwhisper.so/dylib, libggml*.so/dylib)
if (whisperDir) allPaths.push(whisperDir);
allPaths.push(...cudaPaths);
// Linux: LD_LIBRARY_PATH, macOS: DYLD_LIBRARY_PATH
const isMac = process.platform === 'darwin';
const envVar = isMac ? 'DYLD_LIBRARY_PATH' : 'LD_LIBRARY_PATH';
const existingPath = process.env[envVar] || '';
allPaths.push(...existingPath.split(':').filter(Boolean));
// Deduplicate
const uniquePaths = [...new Set(allPaths)];
if (uniquePaths.length === 0) return undefined;
const newPath = uniquePaths.join(':');
console.log(`[Spawn Env] ${envVar}:`, newPath);
return { ...process.env, [envVar]: newPath };
}
function resolveDevice(requestedDevice) {
const req = (requestedDevice || 'auto').toLowerCase();
if (req === 'auto') {
return isCudaAvailable() ? 'cuda' : 'cpu';
}
if (req === 'cuda' && !isCudaAvailable()) {
return 'cpu';
}
if (req !== 'cuda' && req !== 'cpu') {
return 'cpu';
}
return req;
}
// Dynamic performance settings based on system specs (reserved for future use)
function _getOptimalWhisperSettings(device) {
const totalMemory = os.totalmem() / (1024 * 1024 * 1024); // GB
const cpuCores = os.cpus().length;
console.log(`[System Info] RAM: ${totalMemory.toFixed(1)}GB, CPU Cores: ${cpuCores}`);
if (device === 'cuda') {
// GPU settings - balanced for stability and performance
if (totalMemory >= 16 && cpuCores >= 8) {
// High-end system - good performance with safety margin
console.log('[Performance] High-end GPU settings applied');
return [
'--compute_type', 'float16',
'--beam_size', '5',
'--batch_size', '16',
'--threads', '4',
'--chunk_length', '30'
];
} else if (totalMemory >= 8) {
// Mid-range system - balanced settings
console.log('[Performance] Mid-range GPU settings applied');
return [
'--compute_type', 'float16',
'--beam_size', '3',
'--batch_size', '8',
'--threads', '2',
'--chunk_length', '25'
];
} else {
// Low-end system with GPU - conservative but faster than CPU
console.log('[Performance] Low-end GPU settings applied');
return [
'--compute_type', 'int8',
'--beam_size', '1',
'--batch_size', '4',
'--threads', '1',
'--chunk_length', '20'
];
}
} else {
// CPU settings - optimized for different CPU configurations
if (totalMemory >= 16 && cpuCores >= 8) {
// High-end CPU system
console.log('[Performance] High-end CPU settings applied');
return [
'--compute_type', 'int8',
'--beam_size', '3',
'--batch_size', '8',
'--threads', Math.min(cpuCores - 2, 6).toString(),
'--chunk_length', '25'
];
} else if (totalMemory >= 8 && cpuCores >= 4) {
// Mid-range CPU system
console.log('[Performance] Mid-range CPU settings applied');
return [
'--compute_type', 'int8',
'--beam_size', '2',
'--batch_size', '4',
'--threads', Math.min(cpuCores - 1, 4).toString(),
'--chunk_length', '20'
];
} else {
// Low-end CPU system
console.log('[Performance] Low-end CPU settings applied');
return [
'--compute_type', 'int8',
'--beam_size', '1',
'--batch_size', '2',
'--threads', '1',
'--chunk_length', '15'
];
}
}
}
// Enhanced memory/GPU cleanup across files (파일 간 메모리/GPU 정리)
function forceMemoryCleanup(device, isFileTransition = false) {
return new Promise(resolve => {
const cleanupType = isFileTransition ? 'Inter-file memory cleanup' : 'General memory cleanup';
console.log(`${cleanupType} starting...`);
try {
// 1. Kill current process
if (currentProcess && !currentProcess.killed) {
currentProcess.kill('SIGKILL');
currentProcess = null;
console.log(' - Current process killed');
}
if (process.platform === 'win32') {
// 2. Kill all related processes
try {
execSync(`taskkill /F /IM ${WHISPER_CLI_NAME} /T`, { stdio: 'ignore' });
execSync('taskkill /F /IM ffmpeg.exe /T', { stdio: 'ignore' });
console.log(' - All related processes cleaned up');
} catch (_e) {
console.log(' - No processes to clean up');
}
// 3. Enhanced GPU cleanup for CUDA
if (device === 'cuda') {
const delay = isFileTransition ? 2000 : 500; // Longer delay for file transitions
setTimeout(() => {
try {
console.log(' - Flushing GPU cache...');
// Kill all CUDA processes first
try {
execSync('taskkill /F /IM "nvcc.exe" /T', { stdio: 'ignore' });
execSync('taskkill /F /IM "nvidia-smi.exe" /T', { stdio: 'ignore' });
console.log(' - CUDA processes cleaned up');
} catch (e) {
console.log('[GPU] CUDA process cleanup failed:', e.message);
}
// Multiple GPU reset attempts with different methods
for (let i = 0; i < 5; i++) {
try {
if (i < 3) {
execSync('nvidia-smi --gpu-reset', { stdio: 'ignore', timeout: 15000 });
} else {
execSync('nvidia-smi -r', { stdio: 'ignore', timeout: 10000 });
}
console.log(` - GPU reset attempt ${i+1}/5 succeeded`);
break;
} catch (_e) {
if (i === 4) console.log(' - GPU reset failed, continuing');
}
}
console.log(' - GPU memory cleanup completed');
} catch (e) {
console.log(` - GPU cleanup attempt failed: ${e.message}`);
}
// 4. System memory cleanup
try {
execSync('powershell -Command "[System.GC]::Collect(); [System.GC]::WaitForPendingFinalizers();"', {
stdio: 'ignore',
timeout: 5000
});
console.log(' - System memory cleanup completed');
} catch (_e) {
console.log(' - System memory cleanup skipped');
}
resolve();
}, delay);
} else {
resolve();
}
} else {
resolve();
}
// 5. Node.js garbage collection
if (global.gc) {
for (let i = 0; i < 5; i++) {
global.gc();
}
console.log(' - Node.js garbage collection completed');
}
} catch (e) {
console.error(`[ERROR] Memory cleanup error: ${e.message}`);
resolve();
}
});
}
// ===== Update Checker (업데이트 알림) =====
const GITHUB_REPO = 'blue-b/WhisperSubTranslate';
const CURRENT_VERSION = require('./package.json').version;
async function checkForUpdates() {
console.log('[Update Check] Starting... Current version:', CURRENT_VERSION);
try {
const response = await axios.get(
`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`,
{ timeout: 10000 }
);
const latestVersion = response.data.tag_name.replace(/^v/, '');
const releaseUrl = response.data.html_url;
const releaseName = response.data.name || `v${latestVersion}`;
// 버전 비교 (semver 간단 비교)
const isNewer = compareVersions(latestVersion, CURRENT_VERSION) > 0;
console.log(`[Update Check] Latest: ${latestVersion}, Current: ${CURRENT_VERSION}, HasUpdate: ${isNewer}`);
return {
hasUpdate: isNewer,
currentVersion: CURRENT_VERSION,
latestVersion,
releaseUrl,
releaseName
};
} catch (error) {
console.log('[Update Check] Failed:', error.message);
return { hasUpdate: false, error: error.message };
}
}
// 간단한 semver 비교 (1.3.3 vs 1.3.4)
function compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const p1 = parts1[i] || 0;
const p2 = parts2[i] || 0;
if (p1 > p2) return 1;
if (p1 < p2) return -1;
}
return 0;
}
// App Initialization
function createWindow() {
mainWindow = new BrowserWindow({
width: 1280, // 더 넓게 (900→1280) - 2열 레이아웃에 적합
height: 800, // 더 높게 (700→800)
minWidth: 1000, // 최소 너비 제한 (UI 깨짐 방지)
minHeight: 650, // 최소 높이 제한
title: 'WhisperSubTranslate', // 윈도우 타이틀
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js'),
webSecurity: false,
devTools: false, // 배포 버전: 개발자 도구 비활성화
},
icon: path.join(__dirname, 'icon.png'),
autoHideMenuBar: true,
show: false, // 준비 완료 전 깜빡임 방지
});
// 창이 준비되면 표시 (깜빡임 방지)
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.loadFile('index.html');
// DOM이 완전히 로드된 후 업데이트 체크 (main → renderer 직접 실행)
mainWindow.webContents.on('did-finish-load', async () => {
console.log('[Update] Page loaded, checking for updates...');
// renderer.js 초기화 대기
await new Promise(resolve => setTimeout(resolve, 2000));
try {
const result = await checkForUpdates();
if (result && result.hasUpdate) {
console.log('[Update] New version found:', result.latestVersion);
// executeJavaScript로 직접 배너 표시 + 전역 변수에 업데이트 정보 저장
mainWindow.webContents.executeJavaScript(`
(function() {
var banner = document.getElementById('updateBanner');
var message = document.getElementById('updateMessage');
var downloadBtn = document.getElementById('updateDownloadBtn');
var laterBtn = document.getElementById('updateLaterBtn');
if (!banner) { console.error('Banner not found'); return; }
// 전역 변수에 업데이트 정보 저장 (언어 변경 시 사용)
window.currentUpdateInfo = {
latestVersion: '${result.latestVersion}',
releaseUrl: '${result.releaseUrl}'
};
var lang = typeof currentUiLang !== 'undefined' ? currentUiLang : 'ko';
var msgs = {
ko: 'v${result.latestVersion} 업데이트가 있습니다',
en: 'v${result.latestVersion} update available',
ja: 'v${result.latestVersion} アップデートがあります',
zh: 'v${result.latestVersion} 更新可用',
pl: 'Dostępna aktualizacja v${result.latestVersion}'
};
var btns = {
ko: ['다운로드', '나중에'], en: ['Download', 'Later'],
ja: ['ダウンロード', '後で'], zh: ['下载', '稍后'],
pl: ['Pobierz', 'Później']
};
message.textContent = msgs[lang] || msgs.ko;
if (downloadBtn) downloadBtn.textContent = (btns[lang] || btns.ko)[0];
if (laterBtn) laterBtn.textContent = (btns[lang] || btns.ko)[1];
banner.style.display = 'flex';
document.body.classList.add('has-update-banner');
if (downloadBtn) downloadBtn.onclick = function() {
window.electronAPI.openExternal('${result.releaseUrl}');
};
if (laterBtn) laterBtn.onclick = function() {
banner.style.display = 'none';
document.body.classList.remove('has-update-banner');
};
console.log('[Update] Banner displayed, info saved to window.currentUpdateInfo');
})();
`);
} else {
console.log('[Update] No update available');
}
} catch (error) {
console.error('[Update] Auto-check failed:', error.message);
}
});
// 개발 모드에서 캐시 비활성화 (파일 변경 즉시 반영)
mainWindow.webContents.session.clearCache();
// F12 개발자 도구 (배포 버전: 비활성화)
// 개발 시에만 아래 코드 주석 해제
// mainWindow.webContents.on('before-input-event', (event, input) => {
// if (input.key === 'F12') {
// mainWindow.webContents.toggleDevTools();
// }
// });
// Translator에 mainWindow 설정 (UI 업데이트용)
translator.setMainWindow(mainWindow);
// 기본 메뉴 제거 (File/Edit/View/Window/Help 등)
try {
Menu.setApplicationMenu(null);
} catch (error) {
console.log('[Menu] Failed to remove application menu:', error.message);
}
try {
mainWindow.setMenuBarVisibility(false);
} catch (error) {
console.log('[Menu] Failed to hide menu bar:', error.message);
}
// 개발자 도구 오픈 비활성화 (F12/단축키)
// 필요 시 개발 빌드에서만 활성화하도록 별도 환경변수로 제어 가능
mainWindow.on('closed', () => {
forceMemoryCleanup('cuda');
mainWindow = null;
});
}
app.whenReady().then(async () => {
if (app.isPackaged === false) {
app.commandLine.appendSwitch('js-flags', '--expose-gc');
}
// 캐시 완전 삭제 (개발 모드에서만)
if (!app.isPackaged) {
try {
const { session } = require('electron');
await session.defaultSession.clearCache();
await session.defaultSession.clearStorageData();
console.log('[Cache] Cleared all cache and storage');
} catch (e) {
console.log('[Cache] Failed to clear cache:', e.message);
}
}
createWindow();
// 자동 업데이트 체크 (배포 환경에서만 적용 가능)
try {
if (autoUpdater) {
autoUpdater.autoDownload = true;
autoUpdater.checkForUpdatesAndNotify();
}
} catch (error) {
console.log('[Auto-Updater] Update check failed:', error.message);
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ===== Safe Temp Directory (유니코드 경로 문제 해결) =====
// spawn()으로 whisper-cli 호출 시 유니코드 경로가 깨지는 문제 해결
// WAV/SRT를 ASCII 경로에 생성 후 원본 위치로 복사
function getSafeTempDir() {
// 1순위: 앱 실행 경로 내 temp (대부분 영어 경로)
const basePath = app.isPackaged ? path.dirname(process.execPath) : __dirname;
const appTemp = path.join(basePath, 'temp');
// ASCII 문자만 있는지 체크 (유니코드 없으면 안전)
if (/^[\x00-\x7F]*$/.test(appTemp)) {
if (!fs.existsSync(appTemp)) {
fs.mkdirSync(appTemp, { recursive: true });
}
return appTemp;
}
// 2순위: 플랫폼별 안전한 fallback 경로
let fallbackTemp;
if (process.platform === 'win32') {
fallbackTemp = path.join('C:', 'Users', 'Public', 'WhisperSubTranslate', 'temp');
} else {
fallbackTemp = path.join(os.tmpdir(), 'WhisperSubTranslate', 'temp');
}
if (!fs.existsSync(fallbackTemp)) {
fs.mkdirSync(fallbackTemp, { recursive: true });
}
return fallbackTemp;
}
// 경로가 ASCII만 포함하는지 체크
function isAsciiPath(filePath) {
return /^[\x00-\x7F]*$/.test(filePath);
}
// ===== Long Audio Splitting (장시간 오디오 분할 처리) =====
const SEGMENT_DURATION = 30 * 60; // 30분 (초)
const OVERLAP_DURATION = 5; // 5초 오버랩 (경계 자막 누락 방지)
// 영상/오디오 길이 확인 (ffprobe 사용)
function getMediaDuration(inputPath) {
return new Promise((resolve, reject) => {
const basePath = app.isPackaged ? process.resourcesPath : __dirname;
let ffprobePath = 'ffprobe';
// ffprobe 경로 설정 (우선순위: ffprobe-static > 로컬 파일 > 시스템 PATH)
if (ffprobeStaticPath && fs.existsSync(ffprobeStaticPath)) {
ffprobePath = ffprobeStaticPath;
console.log('[Media] Using ffprobe-static');
} else {
const localFfprobe = path.join(basePath, process.platform === 'win32' ? 'ffprobe.exe' : 'ffprobe');
if (fs.existsSync(localFfprobe)) {
ffprobePath = localFfprobe;
console.log('[Media] Using local ffprobe');
} else {
console.log('[Media] Using system PATH ffprobe');
}
}
const args = [
'-v', 'error',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
inputPath
];
const proc = spawn(ffprobePath, args, { windowsHide: true });
let output = '';
const probeTimeout = setTimeout(() => {
if (proc && !proc.killed) {
console.log('[Media] ffprobe timeout, proceeding without split');
proc.kill('SIGKILL');
}
}, 30000);
proc.stdout.on('data', (data) => {
output += data.toString();
});
proc.on('close', (code) => {
clearTimeout(probeTimeout);
if (code === 0) {
const duration = parseFloat(output.trim());
if (!isNaN(duration)) {
console.log(`[Media] Duration: ${duration.toFixed(1)}s (${(duration/60).toFixed(1)} min)`);
resolve(duration);
} else {
reject(new Error('Failed to parse duration'));
}
} else {
// ffprobe 실패 시 분할 없이 진행
console.log('[Media] ffprobe failed, proceeding without split');
resolve(0);
}
});
proc.on('error', () => {
clearTimeout(probeTimeout);
console.log('[Media] ffprobe not found, proceeding without split');
resolve(0);
});
});
}
// 오디오를 여러 세그먼트로 분할
async function splitAudioToSegments(wavPath, duration) {
const segments = [];
const safeTempDir = getSafeTempDir();
// 분할이 필요 없으면 원본 반환
if (duration <= SEGMENT_DURATION + 60) { // 31분 이하면 분할 안 함
return [{ path: wavPath, startTime: 0, isOriginal: true }];
}
console.log(`[Split] Splitting ${(duration/60).toFixed(1)} min audio into segments...`);
mainWindow.webContents.send('output-update', `Splitting long audio into segments for stable processing...\n`);
const basePath = app.isPackaged ? process.resourcesPath : __dirname;
let ffmpegPath = ffmpegStaticPath || 'ffmpeg';
const localFfmpeg = path.join(basePath, process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg');
if (fs.existsSync(localFfmpeg)) {
ffmpegPath = localFfmpeg;
}
let currentStart = 0;
let segmentIndex = 0;
while (currentStart < duration) {
const segmentPath = path.join(safeTempDir, `segment_${Date.now()}_${segmentIndex}.wav`);
const segmentDuration = Math.min(SEGMENT_DURATION + OVERLAP_DURATION, duration - currentStart);
try {
await new Promise((res, rej) => {
const args = [
'-y',
'-ss', currentStart.toString(),
'-i', wavPath,
'-t', segmentDuration.toString(),
'-ar', '16000',
'-ac', '1',
'-c:a', 'pcm_s16le',
segmentPath
];
const proc = spawn(ffmpegPath, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
proc.on('close', (code) => {
if (code === 0 && fs.existsSync(segmentPath)) {
res();
} else {
rej(new Error(`Segment ${segmentIndex} creation failed`));
}
});
proc.on('error', rej);
});
segments.push({
path: segmentPath,
startTime: currentStart,
isOriginal: false
});
console.log(`[Split] Created segment ${segmentIndex + 1}: ${currentStart}s - ${currentStart + segmentDuration}s`);
mainWindow.webContents.send('output-update', `Created segment ${segmentIndex + 1}/${Math.ceil(duration / SEGMENT_DURATION)}\n`);
segmentIndex++;
currentStart += SEGMENT_DURATION; // 다음 세그먼트 시작 (오버랩 포함)
} catch (err) {
// 분할 실패 시 이미 생성된 세그먼트 정리 후 원본으로 진행
console.error('[Split] Segment creation failed:', err.message);
for (const seg of segments) {
try { fs.unlinkSync(seg.path); } catch (_e) { /* ignore */ }
}
return [{ path: wavPath, startTime: 0, isOriginal: true }];
}
}
console.log(`[Split] Created ${segments.length} segments`);
return segments;
}
// SRT 타임스탬프 조정 (오프셋 추가)
function adjustSrtTimestamps(srtContent, offsetSeconds) {
if (offsetSeconds === 0) return srtContent;
const lines = srtContent.split('\n');
const result = [];
// SRT 타임스탬프 형식: 00:00:00,000 --> 00:00:00,000
const timestampRegex = /(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})/;
for (const line of lines) {
const match = line.match(timestampRegex);
if (match) {
const startMs = (parseInt(match[1]) * 3600 + parseInt(match[2]) * 60 + parseInt(match[3])) * 1000 + parseInt(match[4]);
const endMs = (parseInt(match[5]) * 3600 + parseInt(match[6]) * 60 + parseInt(match[7])) * 1000 + parseInt(match[8]);
const newStartMs = startMs + (offsetSeconds * 1000);
const newEndMs = endMs + (offsetSeconds * 1000);
const formatTime = (ms) => {
const hours = Math.floor(ms / 3600000);
const mins = Math.floor((ms % 3600000) / 60000);
const secs = Math.floor((ms % 60000) / 1000);
const millis = ms % 1000;
return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')},${millis.toString().padStart(3, '0')}`;
};
result.push(`${formatTime(newStartMs)} --> ${formatTime(newEndMs)}`);
} else {
result.push(line);
}
}
return result.join('\n');
}
// 여러 SRT 파일 합치기 (중복 제거 포함)
function mergeSrtFiles(srtContents, startTimes) {
const allEntries = [];
for (let i = 0; i < srtContents.length; i++) {
const content = srtContents[i];
const offsetSeconds = startTimes[i];
const adjustedContent = adjustSrtTimestamps(content, offsetSeconds);
// SRT 엔트리 파싱
const entries = parseSrtEntries(adjustedContent);
allEntries.push(...entries);
}
// 시작 시간 기준 정렬
allEntries.sort((a, b) => a.startMs - b.startMs);
// 중복 제거 (오버랩 구간에서 같은 자막이 양쪽 세그먼트에 중복 인식됨)
// 시간 + 텍스트 유사도 모두 확인하여 실제 다른 대사는 보존
const uniqueEntries = [];
for (const entry of allEntries) {
const isDuplicate = uniqueEntries.some(existing => {
if (Math.abs(existing.startMs - entry.startMs) >= 1500) return false;
const a = existing.text.trim().toLowerCase();
const b = entry.text.trim().toLowerCase();
if (!a || !b) return false;
if (a === b) return true;
// 길이 비율이 비슷하고(±30%) 한쪽이 다른쪽을 포함하면 중복
const ratio = Math.min(a.length, b.length) / Math.max(a.length, b.length);
if (ratio < 0.7) return false;
const shorter = a.length < b.length ? a : b;
const longer = a.length < b.length ? b : a;
return longer.includes(shorter);
});
if (!isDuplicate) {
uniqueEntries.push(entry);
}
}
// SRT 형식으로 재생성
let result = '';
for (let i = 0; i < uniqueEntries.length; i++) {
const entry = uniqueEntries[i];
result += `${i + 1}\n`;
result += `${entry.timestamp}\n`;
result += `${entry.text}\n\n`;
}
return result.trim();
}
// SRT 엔트리 파싱 헬퍼
function parseSrtEntries(srtContent) {
const entries = [];
const normalized = srtContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const blocks = normalized.trim().split(/\n\n+/);
for (const block of blocks) {
const lines = block.split('\n');
if (lines.length >= 3) {
const timestampLine = lines[1];
const timestampRegex = /(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const match = timestampLine.match(timestampRegex);
if (match) {
const startMs = (parseInt(match[1]) * 3600 + parseInt(match[2]) * 60 + parseInt(match[3])) * 1000 + parseInt(match[4]);
const text = lines.slice(2).join('\n');
entries.push({
startMs,
timestamp: timestampLine,
text
});
}
}
}
return entries;
}
// 단일 세그먼트 처리 (분할 처리용)
function processSegment(segmentPath, modelPath, device, language, whisperDir, exePath) {
return new Promise((resolve, reject) => {
const safeTempDir = getSafeTempDir();
const tempBaseName = `segment_out_${Date.now()}`;
const outputBase = path.join(safeTempDir, tempBaseName);
const srtPath = outputBase + '.srt';
const args = [
'-m', modelPath,
'-f', segmentPath,
'-osrt',
'-of', outputBase,
...getWhisperCppSettings(device),
];
if (language && language !== 'auto') {
args.push('-l', language);
} else {
args.push('-l', 'auto');
}
console.log(`[Segment] Processing: ${path.basename(segmentPath)}`);
const spawnEnv = getWhisperSpawnEnv(device, whisperDir);
const proc = spawn(exePath, args, {
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
cwd: whisperDir,
...(spawnEnv ? { env: spawnEnv } : {})
});
currentProcess = proc;
const segTimeout = setTimeout(() => {
if (proc && !proc.killed) {
console.log(`[Segment TIMEOUT] ${path.basename(segmentPath)} - exceeded 30 min`);
proc.kill('SIGKILL');
}
}, 1800000);
proc.stdout.on('data', (data) => {
mainWindow.webContents.send('output-update', data.toString('utf8'));
});
proc.stderr.on('data', (data) => {
const output = data.toString('utf8');
if (output.includes('error') || output.includes('Error')) {
mainWindow.webContents.send('output-update', '[ERROR] ' + output);
} else {
mainWindow.webContents.send('output-update', output);
}
});
proc.on('close', (code) => {
clearTimeout(segTimeout);
if (isUserStopped) {
return reject(new Error('Stopped by user'));
}
if ((code === 0 || fs.existsSync(srtPath)) && fs.existsSync(srtPath)) {
try {
const content = fs.readFileSync(srtPath, 'utf-8');
// 임시 SRT 파일 삭제
try { fs.unlinkSync(srtPath); } catch (_e) { /* ignore */ }
resolve(content);
} catch (err) {
reject(new Error(`Failed to read segment SRT: ${err.message}`));
}
} else {
let segError = `Segment processing failed (code: ${code})`;
if (code === 127 && process.platform !== 'win32') {
segError += '. Required shared libraries (.so) not found. ' +
'Ensure libwhisper.so and libggml*.so are in whisper-cpp/ folder.';
}
reject(new Error(segError));
}
});
proc.on('error', (err) => {
clearTimeout(segTimeout);
reject(err);
});
});
}
// ===== Audio Conversion Helper (오디오 변환 헬퍼) =====
// 유니코드 경로 문제 해결: 안전한 temp 경로에 WAV 생성
function convertToWav(inputPath) {
return new Promise((resolve, reject) => {
// 원본 경로가 ASCII인지 확인
const originalWavPath = inputPath.replace(/\.[^/.]+$/, '.wav');
let wavPath;
let usingSafeTemp = false;
if (isAsciiPath(inputPath)) {
// ASCII 경로면 원본 위치에 생성
wavPath = originalWavPath;
} else {
// 유니코드 경로면 안전한 temp에 생성
const safeTempDir = getSafeTempDir();
wavPath = path.join(safeTempDir, `whisper_${Date.now()}.wav`);
usingSafeTemp = true;
console.log(`[Audio] Unicode path detected, using safe temp: ${wavPath}`);
}
// WAV 파일이 이미 존재하면 스킵 (원본 위치만 체크)
if (!usingSafeTemp && fs.existsSync(wavPath)) {
console.log(`[Audio] WAV already exists: ${path.basename(wavPath)}`);
resolve({ wavPath, usingSafeTemp, originalWavPath });
return;
}
console.log(`[Audio] Converting to WAV: ${path.basename(inputPath)}`);
mainWindow.webContents.send('output-update', `Converting audio to WAV format...\n`);