-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_iv_gui.py
More file actions
710 lines (617 loc) · 26.5 KB
/
Copy pathprocess_iv_gui.py
File metadata and controls
710 lines (617 loc) · 26.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
IV Data Batch Processor - GUI
==============================
Photodiode IV test data processing with graphical interface.
Transform: V = -V_original, I = |I_original|
Output: Excel (.xlsx) per file, with Sweep1/Sweep2/Combined sheets.
"""
import os
import sys
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path
# ============================================================
# Import core processor
# ============================================================
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, SCRIPT_DIR)
try:
from process_iv_data import parse_iv_file, write_excel, write_merged_excel
except ImportError:
# Fallback: inline the core functions
import openpyxl
from datetime import datetime
AREA_CM2 = 0.0706858
def parse_iv_file(filepath):
sweep1, sweep2 = [], []
filename = os.path.basename(filepath)
content = None
for encoding in ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'latin-1']:
try:
with open(filepath, 'r', encoding=encoding) as f:
content = f.readlines()
break
except (UnicodeDecodeError, UnicodeError):
continue
if content is None:
raise ValueError(f"Cannot detect encoding: {filename}")
for line in content:
line = line.strip()
if not line:
continue
parts = line.split('\t')
if len(parts) < 3:
continue
if parts[0].strip().lower() == 'index':
continue
try:
index = parts[0].strip()
v_orig = float(parts[1].strip())
i_orig = float(parts[2].strip())
except (ValueError, IndexError):
continue
v_proc = -v_orig
i_proc = abs(i_orig)
i_orig_nAcm2 = i_orig * 1e9 / AREA_CM2
i_proc_nAcm2 = i_proc * 1e9 / AREA_CM2
row = (index, v_orig, i_orig, i_orig_nAcm2, v_proc, i_proc, i_proc_nAcm2)
if index.startswith('2/'):
sweep2.append(row)
else:
sweep1.append(row)
return {'filename': filename, 'filepath': filepath, 'sweep1': sweep1, 'sweep2': sweep2}
def _write_sheet(ws, data):
headers = ['Index', 'V_original(V)', 'I_original(A)', 'I_original(nA/cm²)',
'V_processed(V)', 'I_processed(A)', 'I_processed(nA/cm²)']
ws.append(headers)
for row in data:
ws.append(list(row))
for row in ws.iter_rows(min_row=2, min_col=2, max_col=7):
for cell in row:
cell.number_format = '0.00E+00'
for col in ws.columns:
max_len = 0
col_letter = col[0].column_letter
for cell in col:
try:
max_len = max(max_len, len(str(cell.value)))
except Exception:
pass
ws.column_dimensions[col_letter].width = min(max_len + 4, 30)
def write_excel(parsed_data, output_path):
wb = openpyxl.Workbook()
if parsed_data['sweep1']:
ws1 = wb.active
ws1.title = 'Sweep1'
_write_sheet(ws1, parsed_data['sweep1'])
if parsed_data['sweep2']:
ws2 = wb.create_sheet('Sweep2')
_write_sheet(ws2, parsed_data['sweep2'])
if parsed_data['sweep1'] and parsed_data['sweep2']:
all_data = parsed_data['sweep1'] + parsed_data['sweep2']
ws3 = wb.create_sheet('Combined')
_write_sheet(ws3, all_data)
wb.save(output_path)
def write_merged_excel(all_parsed, output_path):
wb = openpyxl.Workbook()
wb.remove(wb.active)
for data in all_parsed:
fname = os.path.splitext(data['filename'])[0]
prefix = fname[:28]
existing = set(wb.sheetnames)
if data['sweep1']:
name = f"{prefix}_S1"[:31]
if name in existing:
for i in range(2, 100):
if f"{name[:28]}_{i}" not in existing:
name = f"{name[:28]}_{i}"
break
ws = wb.create_sheet(name)
existing.add(name)
_write_sheet(ws, data['sweep1'])
if data['sweep2']:
name = f"{prefix}_S2"[:31]
if name in existing:
for i in range(2, 100):
if f"{name[:28]}_{i}" not in existing:
name = f"{name[:28]}_{i}"
break
ws = wb.create_sheet(name)
existing.add(name)
_write_sheet(ws, data['sweep2'])
if data['sweep1'] and data['sweep2']:
all_data = data['sweep1'] + data['sweep2']
name = f"{prefix}_All"[:31]
if name in existing:
for i in range(2, 100):
if f"{name[:28]}_{i}" not in existing:
name = f"{name[:28]}_{i}"
break
ws = wb.create_sheet(name)
existing.add(name)
_write_sheet(ws, all_data)
wb.save(output_path)
# ============================================================
# Drag & Drop support (Windows)
# ============================================================
try:
import ctypes
from ctypes import wintypes
# Windows API constants
GWL_EXSTYLE = -20
GWL_WNDPROC = -4
WS_EX_ACCEPTFILES = 0x00000010
WM_DROPFILES = 0x0233
_GetWindowLong = ctypes.windll.user32.GetWindowLongW
_GetWindowLong.restype = ctypes.c_long
_SetWindowLong = ctypes.windll.user32.SetWindowLongW
_DragAcceptFiles = ctypes.windll.shell32.DragAcceptFiles
_DragQueryFile = ctypes.windll.shell32.DragQueryFileW
_DragFinish = ctypes.windll.shell32.DragFinish
def _enable_drag_drop(hwnd, callback):
"""Enable Windows file drag-drop on a tk widget by its HWND."""
_DragAcceptFiles(hwnd, True)
# Store callback reference to prevent GC
if not hasattr(_enable_drag_drop, '_callbacks'):
_enable_drag_drop._callbacks = {}
_enable_drag_drop._callbacks[hwnd] = callback
def _handle_wm_dropfiles(hwnd, wparam, lparam):
"""Handle WM_DROPFILES message - extract file paths and invoke callback."""
callback = _enable_drag_drop._callbacks.get(hwnd)
if not callback:
return
nfiles = _DragQueryFile(wparam, 0xFFFFFFFF, None, 0)
files = []
buf = ctypes.create_unicode_buffer(260)
for i in range(nfiles):
_DragQueryFile(wparam, i, buf, 260)
files.append(buf.value)
_DragFinish(wparam)
if files:
callback(files)
# Create a window procedure hook for a specific widget
_original_wndprocs = {}
def _wndproc(hwnd, msg, wparam, lparam):
if msg == WM_DROPFILES:
_handle_wm_dropfiles(hwnd, wparam, lparam)
return 0
# Call original wndproc
orig = _original_wndprocs.get(hwnd)
if orig:
return ctypes.windll.user32.CallWindowProcW(orig, hwnd, msg, wparam, lparam)
return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wparam, lparam)
_WNDPROC = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_uint,
ctypes.c_ulong, ctypes.c_long)
def install_drag_drop(widget, on_files_dropped):
"""Install Windows drag-drop handler on a tk widget. Best-effort."""
try:
widget.update_idletasks()
hwnd = widget.winfo_id()
exstyle = _GetWindowLong(hwnd, GWL_EXSTYLE)
_SetWindowLong(hwnd, GWL_EXSTYLE, exstyle | WS_EX_ACCEPTFILES)
cb = _WNDPROC(_wndproc)
old_proc = ctypes.windll.user32.SetWindowLongW(hwnd, GWL_WNDPROC,
ctypes.cast(cb, ctypes.c_void_p).value)
_original_wndprocs[hwnd] = old_proc
_enable_drag_drop(hwnd, on_files_dropped)
except Exception:
pass # Drag-drop unavailable; browse buttons still work
except (ImportError, AttributeError, OSError):
def install_drag_drop(widget, on_files_dropped):
"""Drag-drop not available on this platform."""
pass
# ============================================================
# GUI Application
# ============================================================
class IVProcessorApp:
"""Main GUI application."""
# -- Colors & styling --
BG = '#f0f2f5'
HEADER_BG = '#1a5276'
HEADER_FG = '#ffffff'
ACCENT = '#2980b9'
ACCENT_HOVER = '#1a6da0'
SUCCESS = '#27ae60'
FAIL = '#e74c3c'
LIST_BG = '#ffffff'
LOG_BG = '#1e1e1e'
LOG_FG = '#d4d4d4'
DROP_ZONE_BG = '#e8f0fe'
DROP_ZONE_BORDER = '#2980b9'
def __init__(self, root):
self.root = root
self.root.title("IV Data Batch Processor")
self.root.geometry("760x640")
self.root.minsize(620, 500)
self.root.configure(bg=self.BG)
# State
self.files = [] # list of (filepath,)
self.processing = False
self.cancel_flag = False
# Set icon if available
try:
self.root.iconbitmap(default='')
except Exception:
pass
self._build_ui()
# Install drag-drop on the main window
install_drag_drop(self.root, self._on_files_dropped)
# ==========================================================
# UI Construction
# ==========================================================
def _build_ui(self):
"""Build all UI components."""
# -- Header --
header = tk.Frame(self.root, bg=self.HEADER_BG, height=72)
header.pack(fill=tk.X)
header.pack_propagate(False)
tk.Label(
header, text="IV Data Batch Processor",
font=('Segoe UI', 18, 'bold'),
bg=self.HEADER_BG, fg=self.HEADER_FG
).pack(pady=(12, 0))
tk.Label(
header, text="V = -V_original I = |I_original| I(nA/cm²) = I×10⁹/0.0706858 -> Excel (.xlsx)",
font=('Segoe UI', 10),
bg=self.HEADER_BG, fg='#a9cce3'
).pack()
# -- Main content --
main = tk.Frame(self.root, bg=self.BG, padx=16, pady=12)
main.pack(fill=tk.BOTH, expand=True)
# === File list ===
file_frame = tk.LabelFrame(
main, text=" Files to Process ", font=('Segoe UI', 10, 'bold'),
bg=self.BG, fg='#2c3e50', padx=8, pady=6
)
file_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 8))
# Drop zone
self.drop_zone = tk.Frame(file_frame, bg=self.DROP_ZONE_BG,
highlightbackground=self.DROP_ZONE_BORDER,
highlightthickness=1, height=28)
self.drop_zone.pack(fill=tk.X, pady=(0, 4))
tk.Label(
self.drop_zone, text="Drag & drop .txt files or folders here",
font=('Segoe UI', 9, 'italic'), bg=self.DROP_ZONE_BG, fg='#555'
).pack(expand=True)
install_drag_drop(self.drop_zone, self._on_files_dropped)
# Listbox + scrollbar
list_container = tk.Frame(file_frame, bg=self.BG)
list_container.pack(fill=tk.BOTH, expand=True)
self.listbox = tk.Listbox(
list_container, font=('Consolas', 9), bg=self.LIST_BG,
selectbackground=self.ACCENT, selectforeground='white',
activestyle='none', relief=tk.FLAT, highlightthickness=1,
highlightcolor='#ccc', highlightbackground='#ddd'
)
self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
list_scroll = ttk.Scrollbar(list_container, orient=tk.VERTICAL,
command=self.listbox.yview)
list_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.listbox.configure(yscrollcommand=list_scroll.set)
# File buttons
btn_row = tk.Frame(file_frame, bg=self.BG)
btn_row.pack(fill=tk.X, pady=(6, 0))
self._make_btn(btn_row, "Add Files", self._add_files, '#3498db').pack(side=tk.LEFT, padx=(0, 6))
self._make_btn(btn_row, "Add Folder", self._add_folder, '#2ecc71').pack(side=tk.LEFT, padx=(0, 6))
self._make_btn(btn_row, "Remove Selected", self._remove_selected, '#e67e22').pack(side=tk.LEFT, padx=(0, 6))
self._make_btn(btn_row, "Clear All", self._clear_files, '#95a5a6').pack(side=tk.LEFT)
self.file_count_label = tk.Label(
btn_row, text="0 files", font=('Segoe UI', 9),
bg=self.BG, fg='#888'
)
self.file_count_label.pack(side=tk.RIGHT)
# === Settings row ===
settings = tk.Frame(main, bg=self.BG)
settings.pack(fill=tk.X, pady=(2, 8))
# Mode
mode_frame = tk.LabelFrame(
settings, text=" Output Mode ", font=('Segoe UI', 9, 'bold'),
bg=self.BG, fg='#2c3e50', padx=10, pady=4
)
mode_frame.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.mode_var = tk.StringVar(value='individual')
ttk.Radiobutton(mode_frame, text="Individual files (one .xlsx per .txt)",
variable=self.mode_var, value='individual').pack(anchor=tk.W)
ttk.Radiobutton(mode_frame, text="Merge into one Excel",
variable=self.mode_var, value='merge').pack(anchor=tk.W)
# Output dir
out_frame = tk.LabelFrame(
settings, text=" Output ", font=('Segoe UI', 9, 'bold'),
bg=self.BG, fg='#2c3e50', padx=10, pady=4
)
out_frame.pack(side=tk.RIGHT, fill=tk.X, padx=(12, 0))
self.out_var = tk.StringVar(value='')
out_row = tk.Frame(out_frame, bg=self.BG)
out_row.pack(fill=tk.X)
tk.Entry(out_row, textvariable=self.out_var, font=('Segoe UI', 9),
state='readonly', readonlybackground='white', relief=tk.FLAT,
highlightthickness=1, highlightcolor='#ccc',
highlightbackground='#ddd').pack(side=tk.LEFT, fill=tk.X, expand=True)
self._make_btn(out_row, "Browse", self._browse_output, '#7f8c8d', height=26).pack(side=tk.LEFT, padx=(4, 0))
tk.Label(out_frame, text="Leave blank to save beside source files",
font=('Segoe UI', 8), bg=self.BG, fg='#999').pack(anchor=tk.W)
# === Progress bar ===
self.progress = ttk.Progressbar(main, mode='determinate')
self.progress.pack(fill=tk.X, pady=(2, 6))
# === Log area ===
log_frame = tk.LabelFrame(
main, text=" Log ", font=('Segoe UI', 10, 'bold'),
bg=self.BG, fg='#2c3e50', padx=8, pady=6
)
log_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 8))
log_container = tk.Frame(log_frame, bg=self.BG)
log_container.pack(fill=tk.BOTH, expand=True)
self.log_text = tk.Text(
log_container, font=('Consolas', 9), bg=self.LOG_BG, fg=self.LOG_FG,
insertbackground='white', relief=tk.FLAT, padx=8, pady=6,
state=tk.DISABLED, wrap=tk.WORD, height=8
)
self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
log_scroll = ttk.Scrollbar(log_container, orient=tk.VERTICAL,
command=self.log_text.yview)
log_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.log_text.configure(yscrollcommand=log_scroll.set)
# Configure log text tags
self.log_text.tag_configure('ok', foreground='#27ae60')
self.log_text.tag_configure('fail', foreground='#e74c3c')
self.log_text.tag_configure('info', foreground='#85c1e9')
self.log_text.tag_configure('warn', foreground='#f39c12')
self.log_text.tag_configure('header', foreground='#f1c40f', font=('Consolas', 10, 'bold'))
# === Action buttons ===
action_row = tk.Frame(main, bg=self.BG)
action_row.pack(fill=tk.X)
self.process_btn = self._make_btn(
action_row, "START PROCESSING", self._process, self.ACCENT,
font=('Segoe UI', 12, 'bold'), height=40
)
self.process_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 8))
self.cancel_btn = self._make_btn(
action_row, "Cancel", self._cancel, '#e74c3c',
font=('Segoe UI', 10), height=40
)
self.cancel_btn.pack(side=tk.RIGHT)
self.cancel_btn.configure(state=tk.DISABLED)
# === Status bar ===
self.status_var = tk.StringVar(value="Ready.")
status = tk.Label(
self.root, textvariable=self.status_var,
font=('Segoe UI', 8), bg='#e0e0e0', fg='#555',
anchor=tk.W, padx=10
)
status.pack(side=tk.BOTTOM, fill=tk.X)
def _make_btn(self, parent, text, command, color, font=None, height=32):
"""Create a styled button."""
if font is None:
font = ('Segoe UI', 9)
btn = tk.Button(
parent, text=text, command=command,
font=font, bg=color, fg='white',
activebackground=self._darken(color),
activeforeground='white',
relief=tk.FLAT, cursor='hand2',
padx=12, height=0 if height > 32 else 1
)
if height:
# tk.Button height is in lines of text - adjust via pady
pass
return btn
@staticmethod
def _darken(hex_color, factor=0.85):
"""Darken a hex color."""
hex_color = hex_color.lstrip('#')
r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
r, g, b = int(r * factor), int(g * factor), int(b * factor)
return f'#{r:02x}{g:02x}{b:02x}'
# ==========================================================
# Actions
# ==========================================================
def _on_files_dropped(self, paths):
"""Handle dropped files/folders."""
added = 0
for path in paths:
if os.path.isfile(path) and path.lower().endswith('.txt'):
if path not in self.files:
self.files.append(path)
added += 1
elif os.path.isdir(path):
for root, dirs, filenames in os.walk(path):
for f in filenames:
if f.lower().endswith('.txt'):
fp = os.path.join(root, f)
if fp not in self.files:
self.files.append(fp)
added += 1
self._refresh_list()
self._log(f"Added {added} file(s) via drag & drop", 'info')
def _add_files(self):
"""Browse and add individual .txt files."""
paths = filedialog.askopenfilenames(
title="Select IV data files",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)
added = 0
for p in paths:
if p not in self.files:
self.files.append(p)
added += 1
self._refresh_list()
self._log(f"Added {added} file(s)", 'info')
def _add_folder(self):
"""Browse and add a folder (scans recursively for .txt)."""
folder = filedialog.askdirectory(title="Select folder containing IV data files")
if not folder:
return
added = 0
for root, dirs, filenames in os.walk(folder):
for f in filenames:
if f.lower().endswith('.txt'):
fp = os.path.join(root, f)
if fp not in self.files:
self.files.append(fp)
added += 1
self._refresh_list()
self._log(f"Scanned folder, added {added} file(s)", 'info')
def _remove_selected(self):
"""Remove selected items from the list."""
selected = self.listbox.curselection()
if not selected:
return
# Remove in reverse order to preserve indices
for i in reversed(selected):
del self.files[i]
self._refresh_list()
self._log(f"Removed {len(selected)} file(s)", 'info')
def _clear_files(self):
"""Clear all files from the list."""
count = len(self.files)
self.files.clear()
self._refresh_list()
self._log(f"Cleared {count} file(s)", 'info')
def _browse_output(self):
"""Browse for output directory."""
folder = filedialog.askdirectory(title="Select output folder")
if folder:
self.out_var.set(folder)
def _refresh_list(self):
"""Refresh the listbox display."""
self.listbox.delete(0, tk.END)
for f in self.files:
self.listbox.insert(tk.END, f" {os.path.basename(f)} - {f}")
count = len(self.files)
self.file_count_label.configure(text=f"{count} file{'s' if count != 1 else ''}")
self.status_var.set(f"{count} file{'s' if count != 1 else ''} loaded.")
# ==========================================================
# Logging
# ==========================================================
def _log(self, msg, tag=''):
"""Append a message to the log area."""
self.log_text.configure(state=tk.NORMAL)
self.log_text.insert(tk.END, msg + '\n', tag)
self.log_text.see(tk.END)
self.log_text.configure(state=tk.DISABLED)
self.root.update_idletasks()
# ==========================================================
# Processing
# ==========================================================
def _process(self):
"""Start processing in a background thread."""
if self.processing:
return
if not self.files:
messagebox.showwarning("No Files", "Please add at least one .txt file to process.")
return
self.processing = True
self.cancel_flag = False
self.process_btn.configure(state=tk.DISABLED)
self.cancel_btn.configure(state=tk.NORMAL)
self.progress.configure(value=0, maximum=len(self.files))
self.log_text.configure(state=tk.NORMAL)
self.log_text.delete('1.0', tk.END)
self.log_text.configure(state=tk.DISABLED)
mode = self.mode_var.get()
out_dir = self.out_var.get() or None
self._log("=" * 56, 'header')
self._log(" IV Data Batch Processor - Started", 'header')
self._log(f" Mode: {'Merge' if mode == 'merge' else 'Individual'}", 'header')
self._log(f" Files: {len(self.files)}", 'header')
self._log("=" * 56, 'header')
self._log("")
thread = threading.Thread(
target=self._run_processing,
args=(mode, out_dir),
daemon=True
)
thread.start()
def _run_processing(self, mode, out_dir):
"""Background processing thread."""
all_parsed = []
success = 0
failed = []
for i, fpath in enumerate(self.files):
if self.cancel_flag:
self._log("\n[WARN] Processing cancelled by user.", 'warn')
break
fname = os.path.basename(fpath)
self._log(f" [{i+1}/{len(self.files)}] {fname} ...", 'info')
try:
data = parse_iv_file(fpath)
s1 = len(data['sweep1'])
s2 = len(data['sweep2'])
if mode == 'merge':
all_parsed.append(data)
self._log(f" Parsed OK - Sweep1: {s1}, Sweep2: {s2}", 'ok')
else:
# Individual mode: write immediately
out_path = os.path.splitext(fpath)[0] + '_processed.xlsx'
if out_dir:
out_path = os.path.join(out_dir, os.path.basename(fpath).replace('.txt', '_processed.xlsx'))
# Ensure unique name
base, ext = os.path.splitext(out_path)
counter = 1
while os.path.exists(out_path):
out_path = f"{base}_{counter}{ext}"
counter += 1
write_excel(data, out_path)
self._log(f" Saved: {os.path.basename(out_path)} (S1:{s1}, S2:{s2})", 'ok')
success += 1
except Exception as e:
self._log(f" FAILED: {e}", 'fail')
failed.append((fname, str(e)))
# Update progress
self.root.after(0, lambda v=i+1: self.progress.configure(value=v))
self.root.after(0, lambda msg=f"{i+1}/{len(self.files)} processed...": self.status_var.set(msg))
# Merge mode: write combined Excel
if mode == 'merge' and all_parsed and not self.cancel_flag:
self._log("\n Writing merged Excel ...", 'info')
try:
if out_dir:
out_path = os.path.join(out_dir, 'all_processed.xlsx')
else:
out_path = os.path.join(os.getcwd(), 'all_processed.xlsx')
write_merged_excel(all_parsed, out_path)
self._log(f" Saved: {out_path}", 'ok')
except Exception as e:
self._log(f" Merge write FAILED: {e}", 'fail')
failed.append(('merge_output', str(e)))
# Summary
self._log("")
self._log("=" * 56, 'header')
self._log(f" Summary: {success} succeeded, {len(failed)} failed", 'header')
if failed:
for fname, err in failed:
self._log(f" - {fname}: {err}", 'fail')
self._log("=" * 56, 'header')
# Reset UI
self.root.after(0, self._processing_done)
def _cancel(self):
"""Cancel ongoing processing."""
self.cancel_flag = True
self.cancel_btn.configure(state=tk.DISABLED)
self._log("\n[Cancelling...]", 'warn')
self.status_var.set("Cancelling...")
def _processing_done(self):
"""Reset UI after processing completes."""
self.processing = False
self.process_btn.configure(state=tk.NORMAL)
self.cancel_btn.configure(state=tk.DISABLED)
self.status_var.set("Done.")
# ============================================================
# Entry point
# ============================================================
def main():
root = tk.Tk()
# Center the window on screen
root.update_idletasks()
w, h = 760, 680
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
x = (sw - w) // 2
y = (sh - h) // 2
root.geometry(f"{w}x{h}+{x}+{y}")
app = IVProcessorApp(root)
root.mainloop()
if __name__ == '__main__':
main()