-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_app.html
More file actions
878 lines (812 loc) · 38.5 KB
/
web_app.html
File metadata and controls
878 lines (812 loc) · 38.5 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
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>σ 조기경보 시계열 데이터 전처리 프로그램 v2.0 (Web)</title>
<meta name="description" content="CSV 파일의 시계열 데이터 필터링, 이상값 처리, 정규화 도구 - 웹 버전">
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{
--bg:#0f1117;--surface:#1a1d27;--surface2:#242836;--surface3:#2e3345;
--border:#363b4e;--text:#e4e6ed;--text2:#9ca0b0;--text3:#6b7084;
--accent:#6c8aff;--accent2:#4a6cf7;--accent-glow:rgba(108,138,255,.15);
--success:#4ade80;--warning:#fbbf24;--error:#f87171;
--radius:10px;--shadow:0 4px 24px rgba(0,0,0,.4);
}
@font-face{font-family:'Inter';src:local('Inter'),local('Apple SD Gothic Neo'),local('Malgun Gothic')}
body{font-family:'Inter','Apple SD Gothic Neo','Malgun Gothic','맑은 고딕',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;line-height:1.5;font-size:14px}
#app{max-width:1100px;margin:0 auto;padding:16px 20px 40px}
/* Header */
.header{display:flex;align-items:center;gap:14px;padding:18px 0 14px;border-bottom:1px solid var(--border);margin-bottom:16px}
.header .logo{font-size:28px;font-weight:800;background:linear-gradient(135deg,var(--accent),#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.header .title{font-size:16px;font-weight:600}
.header .ver{font-size:12px;color:var(--text3);margin-left:auto;background:var(--surface2);padding:4px 10px;border-radius:20px}
/* Section cards */
.section{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:12px;overflow:hidden;transition:border-color .2s}
.section:hover{border-color:var(--accent)}
.section-head{display:flex;align-items:center;gap:8px;padding:10px 16px;background:var(--surface2);font-weight:600;font-size:13px;cursor:pointer;user-select:none}
.section-head .icon{font-size:16px}
.section-body{padding:14px 16px}
/* Buttons */
.btn{display:inline-flex;align-items:center;gap:6px;padding:7px 16px;border-radius:8px;border:1px solid var(--border);background:var(--surface2);color:var(--text);cursor:pointer;font-size:13px;font-weight:500;transition:all .15s}
.btn:hover{background:var(--surface3);border-color:var(--accent)}
.btn:active{transform:scale(.97)}
.btn.primary{background:linear-gradient(135deg,var(--accent2),var(--accent));border-color:var(--accent);color:#fff;font-weight:600}
.btn.primary:hover{box-shadow:0 0 20px var(--accent-glow)}
.btn.success{background:rgba(74,222,128,.15);border-color:var(--success);color:var(--success)}
.btn.danger{background:rgba(248,113,113,.1);border-color:var(--error);color:var(--error)}
.btn:disabled{opacity:.4;pointer-events:none}
/* Inputs */
input,select{background:var(--surface3);border:1px solid var(--border);color:var(--text);padding:6px 10px;border-radius:6px;font-size:13px;outline:none;transition:border-color .15s}
input:focus,select:focus{border-color:var(--accent)}
select{cursor:pointer}
label{display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-size:13px}
input[type=checkbox],input[type=radio]{accent-color:var(--accent);width:15px;height:15px}
/* Drop zone */
.dropzone{border:2px dashed var(--border);border-radius:var(--radius);padding:30px;text-align:center;transition:all .2s;cursor:pointer}
.dropzone.over{border-color:var(--accent);background:var(--accent-glow)}
.dropzone .dz-icon{font-size:36px;margin-bottom:8px}
.dropzone .dz-text{color:var(--text2);font-size:13px}
.file-info{display:flex;align-items:center;gap:10px;padding:8px 0;font-size:13px}
.file-info .badge{background:var(--accent-glow);color:var(--accent);padding:3px 10px;border-radius:14px;font-weight:600;font-size:12px}
/* Preview table */
.table-wrap{overflow-x:auto;margin-top:8px;border-radius:8px;border:1px solid var(--border)}
table{width:100%;border-collapse:collapse;font-size:12px}
th{background:var(--surface3);padding:7px 10px;text-align:left;font-weight:600;position:sticky;top:0;white-space:nowrap}
td{padding:5px 10px;border-top:1px solid var(--border);white-space:nowrap;max-width:120px;overflow:hidden;text-overflow:ellipsis}
tr:hover td{background:var(--surface2)}
/* Filter rows */
.filter-row{display:flex;align-items:center;gap:8px;padding:5px 0;flex-wrap:wrap}
.filter-row select,.filter-row input{width:auto}
.del-btn{background:none;border:none;color:var(--error);cursor:pointer;font-size:16px;padding:2px 6px;border-radius:4px}
.del-btn:hover{background:rgba(248,113,113,.15)}
/* Radio/check groups */
.opt-group{display:flex;gap:16px;flex-wrap:wrap;align-items:center}
.opt-group label{padding:4px 0}
/* Progress */
.progress-bar{width:100%;height:6px;background:var(--surface3);border-radius:3px;overflow:hidden;margin:6px 0}
.progress-fill{height:100%;background:linear-gradient(90deg,var(--accent2),var(--accent));border-radius:3px;transition:width .3s;width:0%}
.progress-text{font-size:12px;color:var(--text2)}
/* Action bar */
.action-bar{display:flex;gap:10px;flex-wrap:wrap;padding:6px 0}
/* Log output */
.log{background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:10px 14px;font-family:'Menlo','Consolas','D2Coding',monospace;font-size:12px;max-height:220px;overflow-y:auto;white-space:pre-wrap;line-height:1.7;color:var(--text2)}
/* Preset modal */
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:1000;display:none;align-items:center;justify-content:center}
.modal-overlay.show{display:flex}
.modal{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:24px;min-width:360px;max-width:500px;box-shadow:var(--shadow)}
.modal h3{margin-bottom:14px;font-size:15px}
.modal input[type=text]{width:100%;margin-bottom:10px}
.modal .modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
.preset-list{max-height:200px;overflow-y:auto}
.preset-item{display:flex;justify-content:space-between;align-items:center;padding:8px 10px;border-radius:6px;cursor:pointer;transition:background .15s}
.preset-item:hover{background:var(--surface2)}
.preset-item .name{font-weight:500}
.preset-item .date{font-size:11px;color:var(--text3)}
/* Toast */
.toast{position:fixed;bottom:24px;right:24px;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:500;z-index:2000;opacity:0;transform:translateY(10px);transition:all .3s;pointer-events:none}
.toast.show{opacity:1;transform:translateY(0)}
.toast.ok{background:rgba(74,222,128,.2);border:1px solid var(--success);color:var(--success)}
.toast.err{background:rgba(248,113,113,.2);border:1px solid var(--error);color:var(--error)}
/* Workflow hint */
.workflow{display:flex;align-items:center;gap:6px;padding:10px 16px;background:linear-gradient(90deg,rgba(108,138,255,.08),transparent);border-radius:8px;font-size:12px;color:var(--text2);margin-bottom:8px}
.workflow b{color:var(--accent);font-size:13px}
/* Responsive */
@media(max-width:700px){#app{padding:10px 12px} .opt-group{gap:10px} .action-bar{flex-direction:column}}
</style>
</head>
<body>
<div id="app">
<!-- HEADER -->
<div class="header">
<span class="logo">σ</span>
<span class="title">조기경보 시계열 데이터 전처리</span>
<span class="ver">Web v2.0</span>
</div>
<!-- WORKFLOW -->
<div class="workflow">
<b>🧭 권장 순서:</b> 1. 파일 열기 → 2. 옵션 설정 → 3. 전처리 실행 → 4. 결과 저장(CSV)
</div>
<!-- FILE SECTION -->
<div class="section" id="sec-file">
<div class="section-head"><span class="icon">📁</span> 파일 선택</div>
<div class="section-body">
<div class="dropzone" id="dropzone">
<div class="dz-icon">📂</div>
<div class="dz-text">CSV 파일을 드래그하거나 클릭해서 선택</div>
<input type="file" id="fileInput" accept=".csv" hidden>
</div>
<div class="file-info" id="fileInfo" style="display:none">
<span id="fileName"></span>
<span class="badge" id="dataSize"></span>
</div>
<div class="table-wrap" id="previewWrap" style="display:none">
<table id="previewTable"><thead id="previewHead"></thead><tbody id="previewBody"></tbody></table>
</div>
</div>
</div>
<!-- FILTER SECTION -->
<div class="section" id="sec-filter">
<div class="section-head"><span class="icon">🔧</span> 필터 조건 (AND 결합)</div>
<div class="section-body">
<div id="filterContainer"></div>
<button class="btn" id="addFilterBtn" onclick="app.addFilter()">+ 필터 추가</button>
</div>
</div>
<!-- OUTLIER SECTION -->
<div class="section" id="sec-outlier">
<div class="section-head"><span class="icon">📊</span> 이상값 처리</div>
<div class="section-body">
<div style="margin-bottom:8px"><b style="font-size:12px;color:var(--text2)">방법:</b></div>
<div class="opt-group" style="margin-bottom:10px">
<label><input type="radio" name="outlierMethod" value="2sigma"> 2σ (95.4%)</label>
<label><input type="radio" name="outlierMethod" value="2.5sigma" checked> 2.5σ (98.8%)</label>
<label><input type="radio" name="outlierMethod" value="3sigma"> 3σ (99.7%)</label>
<label><input type="radio" name="outlierMethod" value="iqr"> IQR</label>
</div>
<div style="font-size:12px;color:var(--text3);margin-bottom:8px">처리: 행 전체 삭제</div>
<label><input type="checkbox" id="applyOutlier" checked> 이상값 처리 적용</label>
</div>
</div>
<!-- NORMALIZE SECTION -->
<div class="section" id="sec-norm">
<div class="section-head"><span class="icon">📈</span> 정규화 (선택사항)</div>
<div class="section-body">
<div class="opt-group">
<label><input type="checkbox" id="applyNormalize"> 정규화 적용</label>
<label><input type="radio" name="normMethod" value="zscore"> Z-Score</label>
<label><input type="radio" name="normMethod" value="minmax" checked> Min-Max (0~1)</label>
</div>
</div>
</div>
<!-- TIME SECTION -->
<div class="section" id="sec-time">
<div class="section-head"><span class="icon">🕐</span> 시간 처리 (선택사항)</div>
<div class="section-body">
<label style="margin-bottom:8px;display:flex"><input type="checkbox" id="applyTimeNorm"> 시간 정규화 (2분 간격 스냅)</label>
<div style="font-size:11px;color:var(--text3);margin:0 0 10px 22px">00:01:00, 00:02:01 같은 시간을 정확한 간격으로 보정</div>
<hr style="border:none;border-top:1px solid var(--border);margin:8px 0">
<label style="margin-bottom:8px;display:flex"><input type="checkbox" id="applyTimeRealign"> 시간 재정렬 (새 시작 시간부터)</label>
<div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:6px">
<label style="font-size:12px">시작 시간: <input type="text" id="startTime" value="" style="width:170px" placeholder="2026-03-13 00:00:00"></label>
<label style="font-size:12px">간격(분): <input type="number" id="interval" value="2" style="width:60px" min="1"></label>
</div>
</div>
</div>
<!-- PROGRESS -->
<div class="section" id="sec-progress">
<div class="section-head"><span class="icon">⏳</span> 진행 상황</div>
<div class="section-body">
<div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
<div class="progress-text" id="progressText">대기 중...</div>
</div>
</div>
<!-- ACTIONS -->
<div class="action-bar">
<button class="btn primary" id="processBtn" onclick="app.runPreprocessing()" disabled>🚀 전처리 실행</button>
<button class="btn success" id="saveBtn" onclick="app.saveFile()" disabled>💾 결과 저장 (CSV)</button>
<button class="btn" onclick="app.showPresetSaveModal()">📋 프리셋 저장</button>
<button class="btn" onclick="app.showPresetLoadModal()">📂 프리셋 불러오기</button>
</div>
<!-- RESULT LOG -->
<div class="section" id="sec-result">
<div class="section-head"><span class="icon">📋</span> 처리 결과</div>
<div class="section-body">
<div class="log" id="logOutput">σ 조기경보 시계열 데이터 전처리 프로그램 (Web v2.0)\n로그 출력 대기 중...\n</div>
</div>
</div>
</div>
<!-- PRESET SAVE MODAL -->
<div class="modal-overlay" id="presetSaveModal">
<div class="modal">
<h3>📋 프리셋 저장</h3>
<input type="text" id="presetNameInput" placeholder="프리셋 이름을 입력하세요">
<div class="modal-actions">
<button class="btn" onclick="app.closeModal('presetSaveModal')">취소</button>
<button class="btn primary" onclick="app.savePreset()">저장</button>
</div>
</div>
</div>
<!-- PRESET LOAD MODAL -->
<div class="modal-overlay" id="presetLoadModal">
<div class="modal">
<h3>📂 프리셋 불러오기</h3>
<div class="preset-list" id="presetList"></div>
<div class="modal-actions">
<button class="btn" onclick="app.closeModal('presetLoadModal')">닫기</button>
</div>
</div>
</div>
<!-- TOAST -->
<div class="toast" id="toast"></div>
<script>
/* ============================================================
DATA PREPROCESSOR - Pure JS Implementation
============================================================ */
class DataPreprocessor {
constructor() {
this.originalData = null; // [{col:val,...},...]
this.processedData = null;
this.columns = [];
this.numericColumns = [];
this.dateColumn = null;
this.stats = {};
this.removedRows = [];
}
// --- CSV Parsing ---
parseCSV(text) {
const lines = text.split(/\r?\n/).filter(l => l.trim() !== '');
if (lines.length < 2) throw new Error('데이터가 부족합니다 (최소 헤더+1행)');
const headers = this._parseLine(lines[0]);
const rows = [];
for (let i = 1; i < lines.length; i++) {
const vals = this._parseLine(lines[i]);
if (vals.length === 0) continue;
const row = {};
for (let j = 0; j < headers.length; j++) {
row[headers[j]] = vals[j] !== undefined ? vals[j] : '';
}
rows.push(row);
}
return { headers, rows };
}
_parseLine(line) {
const result = []; let current = ''; let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (inQuotes) {
if (ch === '"' && line[i+1] === '"') { current += '"'; i++; }
else if (ch === '"') { inQuotes = false; }
else { current += ch; }
} else {
if (ch === '"') { inQuotes = true; }
else if (ch === ',') { result.push(current.trim()); current = ''; }
else { current += ch; }
}
}
result.push(current.trim());
return result;
}
loadData(text) {
const { headers, rows } = this.parseCSV(text);
// Filter out Unnamed columns
const cleanHeaders = headers.filter(h => !h.startsWith('Unnamed'));
this.columns = cleanHeaders;
this.originalData = rows.map(r => {
const o = {};
cleanHeaders.forEach(h => { o[h] = r[h]; });
return o;
});
this.processedData = this.originalData.map(r => ({...r}));
this.removedRows = [];
this._detectDateColumn();
this._detectNumericColumns();
this.stats.original_rows = this.originalData.length;
this.stats.columns = this.columns.length;
return { rows: this.originalData.length, cols: this.columns.length, numCols: this.numericColumns };
}
_detectDateColumn() {
const keywords = ['date','time','datetime','날짜','시간','timestamp'];
this.dateColumn = null;
for (const col of this.columns) {
if (keywords.some(k => col.toLowerCase().includes(k))) {
this.dateColumn = col;
break;
}
}
}
_detectNumericColumns() {
this.numericColumns = [];
if (!this.originalData || this.originalData.length === 0) return;
for (const col of this.columns) {
if (col === this.dateColumn) continue;
// Check first 20 rows for numeric
let numCount = 0;
const sample = Math.min(20, this.originalData.length);
for (let i = 0; i < sample; i++) {
const v = this.originalData[i][col];
if (v !== '' && v !== null && v !== undefined && !isNaN(Number(v))) numCount++;
}
if (numCount > sample * 0.5) {
this.numericColumns.push(col);
if (this.numericColumns.length >= 30) break;
}
}
// Convert numeric columns to numbers
for (const data of [this.originalData, this.processedData]) {
for (const row of data) {
for (const col of this.numericColumns) {
const v = row[col];
row[col] = (v === '' || v === null || v === undefined) ? NaN : Number(v);
}
}
}
}
resetState() {
this.removedRows = [];
this.processedData = this.originalData.map(r => ({...r}));
this.stats.original_rows = this.originalData.length;
this.stats.filtered_rows = this.originalData.length;
this.stats.filter_removed = 0;
this.stats.outliers_removed = 0;
this.stats.rows_after_outlier = this.originalData.length;
}
// --- Stats helpers ---
_mean(arr) { const v = arr.filter(x => !isNaN(x)); return v.length ? v.reduce((a,b) => a+b, 0) / v.length : 0; }
_std(arr) {
const v = arr.filter(x => !isNaN(x)); if (v.length < 2) return 0;
const m = this._mean(v);
return Math.sqrt(v.reduce((s, x) => s + (x - m) ** 2, 0) / (v.length - 1));
}
_quantile(arr, q) {
const v = arr.filter(x => !isNaN(x)).sort((a,b) => a - b);
if (!v.length) return 0;
const pos = (v.length - 1) * q;
const lo = Math.floor(pos), hi = Math.ceil(pos);
return v[lo] + (v[hi] - v[lo]) * (pos - lo);
}
// --- Filtering ---
applyFilters(filters) {
this.processedData = this.originalData.map(r => ({...r}));
const before = this.processedData.length;
if (!filters.length) {
this.stats.filtered_rows = before;
this.stats.filter_removed = 0;
return { success: true, msg: 'ℹ️ 필터 조건 없음 - 전체 데이터 사용' };
}
const kept = []; const removed = [];
for (const row of this.processedData) {
let pass = true;
for (const f of filters) {
const val = Number(row[f.column]);
if (isNaN(val)) { pass = false; break; }
if (f.operator === '>=') { if (!(val >= f.value)) pass = false; }
else if (f.operator === '<=') { if (!(val <= f.value)) pass = false; }
else if (f.operator === '>') { if (!(val > f.value)) pass = false; }
else if (f.operator === '<') { if (!(val < f.value)) pass = false; }
else if (f.operator === '=') { if (val !== f.value) pass = false; }
else if (f.operator === '!=') { if (val === f.value) pass = false; }
else if (f.operator === 'range') { if (!(val >= f.min && val <= f.max)) pass = false; }
if (!pass) break;
}
if (pass) kept.push(row); else removed.push({...row, _reason: 'filter'});
}
if (removed.length) this.removedRows.push(...removed);
this.processedData = kept;
this.stats.filtered_rows = kept.length;
this.stats.filter_removed = before - kept.length;
const pct = before > 0 ? (kept.length / before * 100).toFixed(1) : '0';
return { success: true, msg: `✅ 필터링 완료: ${before} → ${kept.length}행 (${pct}%)` };
}
// --- Outlier removal ---
removeOutliers(method) {
if (!this.processedData) return { success: false, msg: '데이터 없음' };
const sigmaMap = { '2sigma': 2, '2.5sigma': 2.5, '3sigma': 3 };
const before = this.processedData.length;
// Build combined mask
const outlierFlags = new Array(before).fill(false);
for (const col of this.numericColumns) {
const vals = this.processedData.map(r => r[col]);
let lower, upper;
if (method === 'iqr') {
const q1 = this._quantile(vals, 0.25), q3 = this._quantile(vals, 0.75);
const iqr = q3 - q1;
lower = q1 - 1.5 * iqr; upper = q3 + 1.5 * iqr;
} else {
const n = sigmaMap[method] || 2.5;
const m = this._mean(vals), s = this._std(vals);
lower = m - n * s; upper = m + n * s;
}
for (let i = 0; i < before; i++) {
const v = vals[i];
if (!isNaN(v) && (v < lower || v > upper)) outlierFlags[i] = true;
}
}
const kept = []; const removed = [];
for (let i = 0; i < before; i++) {
if (outlierFlags[i]) removed.push({...this.processedData[i], _reason: 'outlier'});
else kept.push(this.processedData[i]);
}
if (removed.length) this.removedRows.push(...removed);
this.processedData = kept;
const count = removed.length;
this.stats.outliers_removed = count;
this.stats.rows_after_outlier = kept.length;
const display = {'2sigma':'2σ (95.4%)','2.5sigma':'2.5σ (98.8%)','3sigma':'3σ (99.7%)','iqr':'IQR'};
return { success: true, msg: `✅ 이상값 처리 완료 (${display[method]||method}): ${count}개 행 제거` };
}
// --- Normalization ---
normalizeData(method) {
if (!this.processedData) return { success: false, msg: '데이터 없음' };
let count = 0;
for (const col of this.numericColumns) {
const vals = this.processedData.map(r => r[col]).filter(v => !isNaN(v));
if (!vals.length) continue;
if (method === 'zscore') {
const m = this._mean(vals), s = this._std(vals);
if (s === 0) continue;
for (const row of this.processedData) {
if (!isNaN(row[col])) row[col] = (row[col] - m) / s;
}
count++;
} else { // minmax
const mn = Math.min(...vals), mx = Math.max(...vals);
if (mx === mn) continue;
for (const row of this.processedData) {
if (!isNaN(row[col])) row[col] = (row[col] - mn) / (mx - mn);
}
count++;
}
}
const names = { zscore: 'Z-Score', minmax: 'Min-Max' };
return { success: true, msg: `✅ 정규화 완료 (${names[method]||method}): ${count}개 컬럼` };
}
// --- Time normalization ---
normalizeTimestamps(intervalMin) {
if (!this.processedData || !this.dateColumn) return { success: false, msg: '날짜 컬럼 없음' };
let corrected = 0;
for (const row of this.processedData) {
const d = new Date(row[this.dateColumn]);
if (isNaN(d.getTime())) continue;
const totalMin = d.getHours() * 60 + d.getMinutes() + d.getSeconds() / 60;
const snapped = Math.round(totalMin / intervalMin) * intervalMin;
const newH = Math.floor((snapped % 1440) / 60);
const newM = Math.floor(snapped % 60);
if (d.getMinutes() !== newM || d.getSeconds() !== 0) corrected++;
const nd = new Date(d);
nd.setHours(newH, newM, 0, 0);
if (snapped >= 1440) nd.setDate(nd.getDate() + Math.floor(snapped / 1440));
row[this.dateColumn] = this._fmtDate(nd);
}
return { success: true, msg: `✅ 시간 정규화 완료: ${corrected}개 보정 (${intervalMin}분 간격)` };
}
realignTimestamps(startTimeStr, intervalMin) {
if (!this.processedData || !this.dateColumn) return { success: false, msg: '날짜 컬럼 없음' };
const start = new Date(startTimeStr.replace(/-/g, '/'));
if (isNaN(start.getTime())) return { success: false, msg: '시작 시간 형식 오류' };
for (let i = 0; i < this.processedData.length; i++) {
const nd = new Date(start.getTime() + i * intervalMin * 60000);
this.processedData[i][this.dateColumn] = this._fmtDate(nd);
}
return { success: true, msg: `✅ 시간 재정렬 완료: ${startTimeStr}부터 ${intervalMin}분 간격, ${this.processedData.length}행` };
}
_fmtDate(d) {
const p = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
getSummary() {
const s = this.stats;
let t = `📊 전처리 결과 요약\n${'─'.repeat(40)}\n`;
if (s.original_rows !== undefined) t += `원본 데이터: ${s.original_rows.toLocaleString()}행\n`;
if (s.filtered_rows !== undefined) t += `필터링 후: ${s.filtered_rows.toLocaleString()}행 (-${(s.filter_removed||0).toLocaleString()})\n`;
if (s.outliers_removed !== undefined) t += `이상값 처리: ${s.outliers_removed.toLocaleString()}개\n`;
if (s.rows_after_outlier !== undefined) t += `최종 데이터: ${s.rows_after_outlier.toLocaleString()}행`;
return t;
}
toCSV() {
if (!this.processedData || !this.processedData.length) return '';
const cols = this.columns.filter(c => !c.startsWith('_'));
const lines = [cols.join(',')];
for (const row of this.processedData) {
const vals = cols.map(c => {
let v = row[c];
if (v === null || v === undefined || (typeof v === 'number' && isNaN(v))) return '';
v = String(v);
if (v.includes(',') || v.includes('"') || v.includes('\n')) v = '"' + v.replace(/"/g, '""') + '"';
return v;
});
lines.push(vals.join(','));
}
return lines.join('\n');
}
getPreview(n = 10) {
const data = this.processedData || this.originalData;
if (!data) return [];
return data.slice(0, n);
}
}
/* ============================================================
PRESET MANAGER - localStorage
============================================================ */
class PresetManager {
constructor(key = 'dp_presets') { this.key = key; }
_getAll() { try { return JSON.parse(localStorage.getItem(this.key) || '[]'); } catch { return []; } }
_saveAll(arr) { localStorage.setItem(this.key, JSON.stringify(arr)); }
save(name, settings) {
const all = this._getAll();
all.unshift({ name, settings, created: new Date().toISOString() });
this._saveAll(all); return true;
}
list() { return this._getAll(); }
load(name) { return this._getAll().find(p => p.name === name) || null; }
remove(name) { this._saveAll(this._getAll().filter(p => p.name !== name)); }
}
/* ============================================================
APP CONTROLLER
============================================================ */
const app = {
dp: new DataPreprocessor(),
pm: new PresetManager(),
filterIdx: 0,
init() {
// Drop zone
const dz = document.getElementById('dropzone');
const fi = document.getElementById('fileInput');
dz.addEventListener('click', () => fi.click());
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('over'); });
dz.addEventListener('dragleave', () => dz.classList.remove('over'));
dz.addEventListener('drop', e => { e.preventDefault(); dz.classList.remove('over'); if (e.dataTransfer.files[0]) this.handleFile(e.dataTransfer.files[0]); });
fi.addEventListener('change', e => { if (e.target.files[0]) this.handleFile(e.target.files[0]); });
// Set default start time
const now = new Date();
const p = n => String(n).padStart(2, '0');
document.getElementById('startTime').value = `${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:00`;
},
handleFile(file) {
if (!file.name.toLowerCase().endsWith('.csv')) {
this.toast('CSV 파일만 지원합니다', true); return;
}
this.progress(10, '파일 읽는 중...');
const reader = new FileReader();
// Try UTF-8 first
reader.onload = () => {
try {
const text = reader.result;
const info = this.dp.loadData(text);
this._onFileLoaded(file, info);
} catch (e) {
// Try EUC-KR / CP949
const reader2 = new FileReader();
reader2.onload = () => {
try {
const info = this.dp.loadData(reader2.result);
this._onFileLoaded(file, info);
} catch (e2) {
this.progress(0, '파일 로드 실패');
this.toast('파일 로드 실패: ' + e2.message, true);
}
};
reader2.readAsText(file, 'euc-kr');
}
};
reader.readAsText(file, 'utf-8');
},
_onFileLoaded(file, info) {
document.getElementById('fileInfo').style.display = 'flex';
document.getElementById('fileName').textContent = '📄 ' + file.name;
document.getElementById('dataSize').textContent = `📊 ${info.rows.toLocaleString()}행 × ${info.cols}열`;
document.getElementById('processBtn').disabled = false;
this.updatePreview();
this.progress(100, '파일 로드 완료!');
this.log(`✅ 파일 로드 완료: ${info.rows.toLocaleString()}행, ${info.cols}열`);
this.log(` 감지된 숫자 컬럼 (${info.numCols.length}개): ${info.numCols.slice(0,10).join(', ')}${info.numCols.length > 10 ? ' ...' : ''}`);
if (info.rows >= 100000) this.log('⚠️ 대용량 데이터 - 처리에 시간이 소요될 수 있습니다.');
},
updatePreview() {
const rows = this.dp.getPreview(10);
if (!rows.length) return;
const cols = this.dp.columns.slice(0, 30);
const head = document.getElementById('previewHead');
const body = document.getElementById('previewBody');
head.innerHTML = '<tr>' + cols.map(c => `<th>${c}</th>`).join('') + '</tr>';
body.innerHTML = rows.map(r => '<tr>' + cols.map(c => {
let v = r[c]; if (v === null || v === undefined || (typeof v === 'number' && isNaN(v))) v = '';
return `<td>${String(v).slice(0, 15)}</td>`;
}).join('') + '</tr>').join('');
document.getElementById('previewWrap').style.display = 'block';
},
// --- Filters ---
addFilter() {
const cols = this.dp.numericColumns;
if (!cols.length) { this.toast('먼저 파일을 로드하세요', true); return; }
const id = this.filterIdx++;
const div = document.createElement('div');
div.className = 'filter-row'; div.id = 'filter-' + id;
div.innerHTML = `
<select id="fcol-${id}">${cols.map(c => `<option>${c}</option>`).join('')}</select>
<select id="fop-${id}" onchange="app.onFilterOpChange(${id})">
<option value="range">range</option>
<option value=">=">>=</option><option value="<="><=</option>
<option value=">">></option><option value="<"><</option>
<option value="=">=</option><option value="!=">!=</option>
</select>
<span id="frange-${id}">
<input type="number" id="fmin-${id}" placeholder="최소" style="width:80px" step="any">
<span style="color:var(--text3)">~</span>
<input type="number" id="fmax-${id}" placeholder="최대" style="width:80px" step="any">
</span>
<span id="fval-${id}" style="display:none">
<input type="number" id="fv-${id}" placeholder="값" style="width:100px" step="any">
</span>
<button class="del-btn" onclick="app.removeFilter(${id})">✕</button>`;
document.getElementById('filterContainer').appendChild(div);
},
onFilterOpChange(id) {
const op = document.getElementById('fop-' + id).value;
document.getElementById('frange-' + id).style.display = op === 'range' ? '' : 'none';
document.getElementById('fval-' + id).style.display = op === 'range' ? 'none' : '';
},
removeFilter(id) {
const el = document.getElementById('filter-' + id);
if (el) el.remove();
},
getFilters() {
const filters = [];
document.querySelectorAll('.filter-row').forEach(row => {
const id = row.id.split('-')[1];
const col = document.getElementById('fcol-' + id)?.value;
const op = document.getElementById('fop-' + id)?.value;
if (!col) return;
if (op === 'range') {
const mn = document.getElementById('fmin-' + id)?.value;
const mx = document.getElementById('fmax-' + id)?.value;
filters.push({ column: col, operator: 'range', min: mn !== '' ? Number(mn) : -Infinity, max: mx !== '' ? Number(mx) : Infinity });
} else {
const v = document.getElementById('fv-' + id)?.value;
if (v !== '') filters.push({ column: col, operator: op, value: Number(v) });
}
});
return filters;
},
// --- Main processing ---
runPreprocessing() {
if (!this.dp.originalData) { this.toast('먼저 파일을 로드하세요', true); return; }
const t0 = performance.now();
this.log('\n' + '='.repeat(50));
this.log(`🔄 전처리 시작... (총 ${this.dp.originalData.length.toLocaleString()}행)`);
this.dp.resetState();
this.progress(10, '필터링 중...');
// Use setTimeout to allow UI updates
setTimeout(() => {
// 1. Filter
const filters = this.getFilters();
const fr = this.dp.applyFilters(filters);
this.log(fr.msg);
this.progress(40, '이상값 처리 중...');
setTimeout(() => {
// 2. Outlier
if (document.getElementById('applyOutlier').checked) {
const method = document.querySelector('input[name=outlierMethod]:checked').value;
const or = this.dp.removeOutliers(method);
this.log(or.msg);
}
this.progress(65, '정규화 중...');
setTimeout(() => {
// 3. Normalize
if (document.getElementById('applyNormalize').checked) {
const nm = document.querySelector('input[name=normMethod]:checked').value;
const nr = this.dp.normalizeData(nm);
this.log(nr.msg);
}
this.progress(80, '시간 처리 중...');
setTimeout(() => {
// 4. Time normalize
const interval = parseInt(document.getElementById('interval').value) || 2;
if (document.getElementById('applyTimeNorm').checked) {
const tr = this.dp.normalizeTimestamps(interval);
this.log(tr.msg);
}
// 5. Time realign
if (document.getElementById('applyTimeRealign').checked) {
const st = document.getElementById('startTime').value;
const tr2 = this.dp.realignTimestamps(st, interval);
this.log(tr2.msg);
}
const elapsed = ((performance.now() - t0) / 1000).toFixed(2);
this.progress(100, '✅ 전처리 완료!');
this.log('');
this.log(this.dp.getSummary());
this.log(`\n⏱ 총 소요 시간: ${elapsed}초`);
this.log('✅ 전처리 완료! "결과 저장(CSV)" 버튼을 눌러 저장하세요.');
this.updatePreview();
document.getElementById('saveBtn').disabled = false;
}, 10);
}, 10);
}, 10);
}, 10);
},
// --- Save ---
saveFile() {
const csv = this.dp.toCSV();
if (!csv) { this.toast('저장할 데이터가 없습니다', true); return; }
const bom = '\uFEFF';
const blob = new Blob([bom + csv], { type: 'text/csv;charset=utf-8' });
const a = document.createElement('a');
const ts = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 15);
a.download = `processed_${ts}.csv`;
a.href = URL.createObjectURL(blob);
a.click();
URL.revokeObjectURL(a.href);
this.log(`\n💾 저장 완료: ${a.download}`);
this.toast('CSV 파일 저장 완료!');
},
// --- Presets ---
getCurrentSettings() {
return {
outlier: {
apply: document.getElementById('applyOutlier').checked,
method: document.querySelector('input[name=outlierMethod]:checked')?.value || '2.5sigma'
},
normalize: {
apply: document.getElementById('applyNormalize').checked,
method: document.querySelector('input[name=normMethod]:checked')?.value || 'minmax'
},
time: {
normalize: document.getElementById('applyTimeNorm').checked,
realign: document.getElementById('applyTimeRealign').checked,
start_time: document.getElementById('startTime').value,
interval: document.getElementById('interval').value
},
filters: this.getFilters()
};
},
applySettings(s) {
if (!s) return;
document.getElementById('applyOutlier').checked = s.outlier?.apply ?? true;
const om = s.outlier?.method || '2.5sigma';
document.querySelectorAll('input[name=outlierMethod]').forEach(r => { r.checked = r.value === om; });
document.getElementById('applyNormalize').checked = s.normalize?.apply ?? false;
const nm = s.normalize?.method || 'minmax';
document.querySelectorAll('input[name=normMethod]').forEach(r => { r.checked = r.value === nm; });
document.getElementById('applyTimeNorm').checked = s.time?.normalize ?? false;
document.getElementById('applyTimeRealign').checked = s.time?.realign ?? false;
if (s.time?.start_time) document.getElementById('startTime').value = s.time.start_time;
if (s.time?.interval) document.getElementById('interval').value = s.time.interval;
},
showPresetSaveModal() { document.getElementById('presetSaveModal').classList.add('show'); document.getElementById('presetNameInput').focus(); },
showPresetLoadModal() {
const list = this.pm.list();
const el = document.getElementById('presetList');
if (!list.length) { el.innerHTML = '<div style="color:var(--text3);padding:16px;text-align:center">저장된 프리셋이 없습니다</div>'; }
else {
el.innerHTML = list.map(p => `<div class="preset-item" onclick="app.loadPreset('${p.name.replace(/'/g,"\\'")}')">
<div><span class="name">${p.name}</span></div>
<div style="display:flex;gap:8px;align-items:center">
<span class="date">${p.created ? new Date(p.created).toLocaleDateString() : ''}</span>
<button class="del-btn" onclick="event.stopPropagation();app.deletePreset('${p.name.replace(/'/g,"\\'")}')">✕</button>
</div></div>`).join('');
}
document.getElementById('presetLoadModal').classList.add('show');
},
closeModal(id) { document.getElementById(id).classList.remove('show'); },
savePreset() {
const name = document.getElementById('presetNameInput').value.trim();
if (!name) { this.toast('이름을 입력하세요', true); return; }
this.pm.save(name, this.getCurrentSettings());
this.closeModal('presetSaveModal');
document.getElementById('presetNameInput').value = '';
this.toast(`프리셋 "${name}" 저장 완료!`);
this.log(`💾 프리셋 저장: ${name}`);
},
loadPreset(name) {
const p = this.pm.load(name);
if (p) { this.applySettings(p.settings); this.closeModal('presetLoadModal'); this.toast(`프리셋 "${name}" 로드 완료!`); this.log(`📂 프리셋 로드: ${name}`); }
},
deletePreset(name) {
this.pm.remove(name);
this.showPresetLoadModal();
this.toast(`프리셋 "${name}" 삭제됨`);
},
// --- UI helpers ---
progress(val, text) {
document.getElementById('progressFill').style.width = val + '%';
document.getElementById('progressText').textContent = text;
},
log(msg) {
const el = document.getElementById('logOutput');
el.textContent += msg + '\n';
el.scrollTop = el.scrollHeight;
},
toast(msg, isErr = false) {
const el = document.getElementById('toast');
el.textContent = msg;
el.className = 'toast show ' + (isErr ? 'err' : 'ok');
clearTimeout(this._toastTimer);
this._toastTimer = setTimeout(() => { el.classList.remove('show'); }, 2500);
}
};
document.addEventListener('DOMContentLoaded', () => app.init());
</script>
</body>
</html>