-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
278 lines (220 loc) · 10.3 KB
/
main.py
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
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd, messagebox
import pandas as pd
import numpy as np
import os
import csv
def main():
root = tk.Tk()
root.title("Patient Data Management")
def open_existing_file():
global fname
fname = fd.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
if fname:
dataf = pd.read_excel(fname)
root.destroy()
display_table(dataf, fname)
def new_project():
dataf = pd.DataFrame(columns=['patient_id', 'age', 'tumor_status', 'file_name'])
root.destroy()
display_table(dataf, None)
open_button = tk.Button(root, text="Open Existing File", command=open_existing_file)
open_button.pack(pady=20)
new_button = tk.Button(root, text="New Project", command=new_project)
new_button.pack(pady=20)
root.mainloop()
def open_file(file_name):
current_directory = os.path.dirname(fname)
file_path = os.path.join(current_directory, file_name + '.tsv')
print(f"Trying to open file at path: {file_path}")
if os.path.exists(file_path):
print("File exists, opening...")
with open(file_path, "r") as file:
reader = csv.reader(file, delimiter="\t")
content = list(reader)
show_table_window(content)
else:
messagebox.showerror("File Not Found", f"File {file_name} not found in the current directory.")
def show_table_window(content):
table_window = tk.Toplevel()
table_window.title("File Content")
tree = ttk.Treeview(table_window)
tree["columns"] = ("#1", "#2", "#3", "#4", "#5")
tree.heading("#0", text="Index")
for i, heading in enumerate(content[0]):
tree.heading("#" + str(i+1), text=heading)
for index, row in enumerate(content[1:], start=1):
tree.insert("", index, text=index, values=row)
tree.pack(expand=True, fill="both")
def display_table(dataf, fname):
root = tk.Tk()
root.title("Patient Data")
frame = tk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True)
tree = ttk.Treeview(frame)
tree["columns"] = ("ID", "Age", "Tumor Status", "File Name", "Open File")
tree.heading("#0", text="")
tree.column("#0", anchor="center", width=0)
tree.heading("ID", text="Patient ID")
tree.column("ID", anchor="center", width=100)
tree.heading("Age", text="Age")
tree.column("Age", anchor="center", width=100)
tree.heading("Tumor Status", text="Tumor Status")
tree.column("Tumor Status", anchor="center", width=100)
tree.heading("File Name", text="File Name")
tree.column("File Name", anchor="center", width=200)
tree.heading("Open File", text="Open File")
tree.column("Open File", anchor="center", width=100)
for i in range(len(dataf)):
tree.insert("", i, text="", values=(dataf.loc[i]['patient_id'], dataf.loc[i]['age'], dataf.loc[i]['tumor_status'], dataf.loc[i]['file_name'], ""))
def on_click(event):
item = tree.selection()[0]
file_name = tree.item(item, "values")[3]
open_file(file_name)
tree.bind("<Double-1>", on_click)
tree.pack(expand=True, fill="both")
button_frame = tk.Frame(root)
button_frame.pack(side=tk.BOTTOM, pady=10)
add_button = tk.Button(button_frame, text="Add Patient", command=lambda: add_patient_window(tree, dataf))
add_button.pack(side=tk.LEFT)
delete_button = tk.Button(button_frame, text="Delete Patient", command=lambda: delete_patient(tree, dataf))
delete_button.pack(side=tk.LEFT, padx=10)
save_button = tk.Button(button_frame, text="Save", command=lambda: save_changes(dataf, fname))
save_button.pack(side=tk.RIGHT)
export_button = tk.Button(root, text="Export to Excel", command=lambda: export_to_excel(dataf))
export_button.pack(side=tk.BOTTOM, pady=10)
edit_button = tk.Button(button_frame, text="Edit Patient", command=lambda: edit_patient(tree, dataf))
edit_button.pack(side=tk.LEFT, padx=10)
new_project_button = tk.Button(button_frame, text="New Project", command=lambda: start_new_project(dataf, root))
new_project_button.pack(side=tk.LEFT, padx=10)
root.mainloop()
def edit_patient(tree, dataf):
selected_item = tree.selection()
if selected_item:
item = tree.selection()[0]
index = int(tree.index(item))
selected_patient = dataf.loc[index]
edit_window = tk.Toplevel()
edit_window.title("Edit Patient Information")
tk.Label(edit_window, text="Patient ID:", fg="red").grid(row=0, column=0)
tk.Label(edit_window, text="Age:", fg="red").grid(row=1, column=0)
tk.Label(edit_window, text="Tumor/Benign:", fg="red").grid(row=2, column=0)
tk.Label(edit_window, text="File Name:", fg="red").grid(row=3, column=0)
patient_id_entry = tk.Entry(edit_window)
age_entry = tk.Entry(edit_window)
tumor_status_combobox = ttk.Combobox(edit_window, values=["Tumor", "Benign"])
tumor_status_combobox.grid(row=2, column=1)
tumor_status_combobox.set(selected_patient['tumor_status'])
file_name_entry = tk.Entry(edit_window)
patient_id_entry.grid(row=0, column=1)
age_entry.grid(row=1, column=1)
file_name_entry.grid(row=3, column=1)
patient_id_entry.insert(0, selected_patient['patient_id'])
age_entry.insert(0, selected_patient['age'])
file_name_entry.insert(0, selected_patient['file_name'])
def update_patient():
patient_id = patient_id_entry.get()
age = age_entry.get()
tumor_status = tumor_status_combobox.get()
file_name = file_name_entry.get()
dataf.at[index, 'patient_id'] = patient_id
dataf.at[index, 'age'] = age
dataf.at[index, 'tumor_status'] = tumor_status
dataf.at[index, 'file_name'] = file_name
edit_window.destroy()
tree.item(item, values=(patient_id, age, tumor_status, file_name, ""))
edit_button = tk.Button(edit_window, text="Update Patient", command=update_patient)
edit_button.grid(row=4, columnspan=2)
def save_changes(dataf, fname):
if fname:
dataf.to_excel(fname, index=False)
print("Changes saved successfully!")
else:
fname = fd.asksaveasfilename(defaultextension=".xlsx", filetypes=[("Excel files", "*.xlsx")])
if fname:
dataf.to_excel(fname, index=False)
print("File saved successfully!")
def export_to_excel(dataf, filename_prefix='output'):
tsdf = dataf['tumor_status']
tsdf.to_excel(filename_prefix + '_labels.xlsx', index=False)
file_name = dataf.loc[0]['file_name']
file_path = os.path.join(os.getcwd(), file_name + '.tsv')
raddf = pd.read_csv(file_path, sep='\t')
raddf = raddf[raddf['Image type'] != 'diagnostics']
featdf = raddf.iloc[:, 0:3]
featdf.to_excel(filename_prefix + '_featurenames.xlsx', index=False)
all_data = []
for file_name in dataf['file_name']:
file_path = os.path.join(os.getcwd(), file_name + '.tsv')
raddf = pd.read_csv(file_path, sep='\t')
raddf = raddf[raddf['Image type'] != 'diagnostics']
featdf = raddf.iloc[:, 3]
all_data.append(featdf.to_numpy().T)
npdata = np.array(all_data)
export_df = pd.DataFrame(npdata)
export_filename = filename_prefix + '_features.xlsx'
export_df.to_excel(export_filename, index=False)
def add_patient_window(tree, dataf):
add_window = tk.Toplevel()
add_window.title("Add New Patient")
tk.Label(add_window, text="Patient ID:", fg="red").grid(row=0, column=0)
tk.Label(add_window, text="Age:", fg="red").grid(row=1, column=0)
tk.Label(add_window, text="Tumor/Benign:", fg="red").grid(row=2, column=0)
tk.Label(add_window, text="File Name:", fg="red").grid(row=3, column=0)
patient_id_entry = tk.Entry(add_window)
age_entry = tk.Entry(add_window)
tumor_status_combobox = ttk.Combobox(add_window, values=["Tumor", "Benign"])
tumor_status_combobox.grid(row=2, column=1)
tumor_status_combobox.set("Tumor")
file_name_entry = tk.Entry(add_window)
patient_id_entry.grid(row=0, column=1)
age_entry.grid(row=1, column=1)
file_name_entry.grid(row=3, column=1)
def choose_file():
file_path = fd.askopenfilename()
if file_path:
try:
file_ext = file_path.split(".")[-1].lower()
if file_ext == "xlsx":
df = pd.read_excel(file_path)
elif file_ext == "tsv":
df = pd.read_csv(file_path, sep='\t')
else:
tk.messagebox.showerror("File Error", "Unsupported file format. Please choose an Excel (xlsx) or TSV file.")
return
num_rows, num_cols = df.shape
if num_rows == 888 and num_cols == 4:
file_name_entry.delete(0, tk.END)
file_name_entry.insert(0, os.path.basename(file_path).split('.')[0])
else:
tk.messagebox.showerror("File Error", f"Selected file should have 888 rows and 4 columns. Please choose a valid file.")
except Exception as e:
tk.messagebox.showerror("File Error", f"Error loading file: {str(e)}")
file_button = tk.Button(add_window, text="Choose File", command=choose_file)
file_button.grid(row=3, column=2)
def add_patient():
patient_id = patient_id_entry.get()
age = age_entry.get()
tumor_status = tumor_status_combobox.get()
file_name = file_name_entry.get()
dataf.loc[len(dataf)] = [patient_id, age, tumor_status, file_name]
add_window.destroy()
tree.delete(*tree.get_children())
for i in range(len(dataf)):
tree.insert("", i, text="", values=(dataf.loc[i]['patient_id'], dataf.loc[i]['age'], dataf.loc[i]['tumor_status'], dataf.loc[i]['file_name'], ""))
add_button = tk.Button(add_window, text="Add Patient", command=add_patient)
add_button.grid(row=4, columnspan=2)
def delete_patient(tree, dataf):
selected_item = tree.selection()
if selected_item:
for item in selected_item:
index = int(tree.index(item))
dataf.drop(index, inplace=True)
tree.delete(selected_item)
def start_new_project(dataf, root):
save_changes(dataf, None)
root.destroy()
main()
if __name__ == "__main__":
main()