spacr 0.1.0__py3-none-any.whl → 0.1.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spacr/annotate_app_v2.py CHANGED
@@ -1,16 +1,18 @@
1
+ import sqlite3
1
2
  from queue import Queue
2
- from tkinter import Label, Entry, Button
3
+ from tkinter import Label
3
4
  import tkinter as tk
5
+ from tkinter import ttk
4
6
  import os, threading, time, sqlite3
5
7
  import numpy as np
6
8
  from PIL import Image, ImageOps
7
9
  from concurrent.futures import ThreadPoolExecutor
8
10
  from PIL import ImageTk
9
- import pandas as pd
10
11
  from skimage.exposure import rescale_intensity
11
- import cv2
12
- import matplotlib.pyplot as plt
13
12
  from IPython.display import display, HTML
13
+ from tkinter import font as tkFont
14
+
15
+ from .gui_utils import ScrollableFrame, CustomButton, set_dark_style, set_default_font, style_text_boxes, create_menu_bar
14
16
 
15
17
  class ImageApp:
16
18
  def __init__(self, root, db_path, src, image_type=None, channels=None, grid_rows=None, grid_cols=None, image_size=(200, 200), annotation_column='annotate', normalize=False, percentiles=(1,99), measurement=None, threshold=None):
@@ -509,3 +511,160 @@ def annotate(settings):
509
511
 
510
512
  app.load_images()
511
513
  root.mainloop()
514
+
515
+ # Global list to keep references to PhotoImage objects
516
+ global_image_refs = []
517
+
518
+ def initiate_annotation_app_root(parent_frame):
519
+ style = ttk.Style(parent_frame)
520
+ set_dark_style(style)
521
+ style_text_boxes(style)
522
+ set_default_font(parent_frame, font_name="Arial", size=8)
523
+
524
+ parent_frame.configure(bg='black')
525
+
526
+ container = tk.PanedWindow(parent_frame, orient=tk.HORIZONTAL, bg='black')
527
+ container.pack(fill=tk.BOTH, expand=True)
528
+
529
+ scrollable_frame = ScrollableFrame(container, bg='black')
530
+ container.add(scrollable_frame, stretch="always")
531
+
532
+ # Setup input fields
533
+ vars_dict = {
534
+ 'src': ttk.Entry(scrollable_frame.scrollable_frame),
535
+ 'image_type': ttk.Entry(scrollable_frame.scrollable_frame),
536
+ 'channels': ttk.Entry(scrollable_frame.scrollable_frame),
537
+ 'geom': ttk.Entry(scrollable_frame.scrollable_frame),
538
+ 'img_size': ttk.Entry(scrollable_frame.scrollable_frame),
539
+ 'rows': ttk.Entry(scrollable_frame.scrollable_frame),
540
+ 'columns': ttk.Entry(scrollable_frame.scrollable_frame),
541
+ 'annotation_column': ttk.Entry(scrollable_frame.scrollable_frame),
542
+ 'normalize': ttk.Entry(scrollable_frame.scrollable_frame),
543
+ 'percentiles': ttk.Entry(scrollable_frame.scrollable_frame),
544
+ 'measurement': ttk.Entry(scrollable_frame.scrollable_frame),
545
+ 'threshold': ttk.Entry(scrollable_frame.scrollable_frame),
546
+ }
547
+
548
+ default_settings = {
549
+ 'src': 'path',
550
+ 'image_type': 'cell_png',
551
+ 'channels': 'r,g,b',
552
+ 'geom': "3200x2000",
553
+ 'img_size': '(200, 200)',
554
+ 'rows': '10',
555
+ 'columns': '18',
556
+ 'annotation_column': 'recruited_test',
557
+ 'normalize': 'False',
558
+ 'percentiles': '(2,98)',
559
+ 'measurement': 'None',
560
+ 'threshold': 'None'
561
+ }
562
+
563
+ # Arrange input fields and labels
564
+ row = 0
565
+ for name, entry in vars_dict.items():
566
+ ttk.Label(scrollable_frame.scrollable_frame, text=f"{name.replace('_', ' ').capitalize()}:",
567
+ background="black", foreground="white").grid(row=row, column=0)
568
+ entry.insert(0, default_settings[name])
569
+ entry.grid(row=row, column=1)
570
+ row += 1
571
+
572
+ # Function to be called when "Run" button is clicked
573
+ def run_app():
574
+ settings = {key: entry.get() for key, entry in vars_dict.items()}
575
+ settings['channels'] = settings['channels'].split(',')
576
+ settings['img_size'] = tuple(map(int, settings['img_size'][1:-1].split(',')))
577
+ settings['percentiles'] = tuple(map(int, settings['percentiles'][1:-1].split(',')))
578
+ settings['normalize'] = settings['normalize'].lower() == 'true'
579
+ settings['rows'] = int(settings['rows'])
580
+ settings['columns'] = int(settings['columns'])
581
+ if settings['measurement'].lower() == 'none':
582
+ settings['measurement'] = None
583
+ if settings['threshold'].lower() == 'none':
584
+ settings['threshold'] = None
585
+
586
+ # Clear previous content instead of destroying the root
587
+ if hasattr(parent_frame, 'winfo_children'):
588
+ for widget in parent_frame.winfo_children():
589
+ widget.destroy()
590
+
591
+ # Start the annotate application in the same root window
592
+ annotate_app(parent_frame, settings)
593
+
594
+ run_button = CustomButton(scrollable_frame.scrollable_frame, text="Run", command=run_app,
595
+ font=tkFont.Font(family="Arial", size=12, weight=tkFont.NORMAL))
596
+ run_button.grid(row=row, column=0, columnspan=2, pady=10, padx=10)
597
+
598
+ return parent_frame
599
+
600
+ def annotate_app(parent_frame, settings):
601
+ global global_image_refs
602
+ global_image_refs.clear()
603
+ root = parent_frame.winfo_toplevel()
604
+ annotate_with_image_refs(settings, root, lambda: load_next_app(root))
605
+
606
+ def annotate_with_image_refs(settings, root, shutdown_callback):
607
+ settings = get_annotate_default_settings(settings)
608
+ src = settings['src']
609
+
610
+ db = os.path.join(src, 'measurements/measurements.db')
611
+ conn = sqlite3.connect(db)
612
+ c = conn.cursor()
613
+ c.execute('PRAGMA table_info(png_list)')
614
+ cols = c.fetchall()
615
+ if settings['annotation_column'] not in [col[1] for col in cols]:
616
+ c.execute(f"ALTER TABLE png_list ADD COLUMN {settings['annotation_column']} integer")
617
+ conn.commit()
618
+ conn.close()
619
+
620
+ app = ImageApp(root, db, src, image_type=settings['image_type'], channels=settings['channels'], image_size=settings['img_size'], grid_rows=settings['rows'], grid_cols=settings['columns'], annotation_column=settings['annotation_column'], normalize=settings['normalize'], percentiles=settings['percentiles'], measurement=settings['measurement'], threshold=settings['threshold'])
621
+
622
+ # Set the canvas background to black
623
+ root.configure(bg='black')
624
+
625
+ next_button = tk.Button(root, text="Next", command=app.next_page, background='black', foreground='white')
626
+ next_button.grid(row=app.grid_rows, column=app.grid_cols - 1)
627
+ back_button = tk.Button(root, text="Back", command=app.previous_page, background='black', foreground='white')
628
+ back_button.grid(row=app.grid_rows, column=app.grid_cols - 2)
629
+ exit_button = tk.Button(root, text="Exit", command=lambda: [app.shutdown(), shutdown_callback()], background='black', foreground='white')
630
+ exit_button.grid(row=app.grid_rows, column=app.grid_cols - 3)
631
+
632
+ app.load_images()
633
+
634
+ # Store the shutdown function and next app details in the root
635
+ root.current_app_exit_func = app.shutdown
636
+ root.next_app_func = None
637
+ root.next_app_args = ()
638
+
639
+ def load_next_app(root):
640
+ # Get the next app function and arguments
641
+ next_app_func = root.next_app_func
642
+ next_app_args = root.next_app_args
643
+
644
+ if next_app_func:
645
+ next_app_func(*next_app_args)
646
+
647
+ def gui_annotate():
648
+ root = tk.Tk()
649
+ width = root.winfo_screenwidth()
650
+ height = root.winfo_screenheight()
651
+ root.geometry(f"{width}x{height}")
652
+ root.title("Annotate Application")
653
+
654
+ # Clear previous content if any
655
+ if hasattr(root, 'content_frame'):
656
+ for widget in root.content_frame.winfo_children():
657
+ widget.destroy()
658
+ root.content_frame.grid_forget()
659
+ else:
660
+ root.content_frame = tk.Frame(root)
661
+ root.content_frame.grid(row=1, column=0, sticky="nsew")
662
+ root.grid_rowconfigure(1, weight=1)
663
+ root.grid_columnconfigure(0, weight=1)
664
+
665
+ initiate_annotation_app_root(root.content_frame)
666
+ create_menu_bar(root)
667
+ root.mainloop()
668
+
669
+ if __name__ == "__main__":
670
+ gui_annotate()
spacr/classify_app.py ADDED
@@ -0,0 +1,201 @@
1
+ import sys, ctypes, matplotlib
2
+ import tkinter as tk
3
+ from tkinter import ttk, scrolledtext
4
+ from matplotlib.figure import Figure
5
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
6
+ from matplotlib.figure import Figure
7
+ matplotlib.use('Agg')
8
+ from tkinter import filedialog
9
+ from multiprocessing import Process, Queue, Value
10
+ import traceback
11
+
12
+ try:
13
+ ctypes.windll.shcore.SetProcessDpiAwareness(True)
14
+ except AttributeError:
15
+ pass
16
+
17
+ from .logger import log_function_call
18
+ from .gui_utils import ScrollableFrame, StdoutRedirector, CustomButton, set_dark_style, set_default_font, generate_fields, process_stdout_stderr, clear_canvas, main_thread_update_function
19
+ from .gui_utils import classify_variables, check_classify_gui_settings, train_test_model_wrapper, read_settings_from_csv, update_settings_from_csv, style_text_boxes, create_menu_bar
20
+
21
+ thread_control = {"run_thread": None, "stop_requested": False}
22
+
23
+ #@log_function_call
24
+ def initiate_abort():
25
+ global thread_control
26
+ if thread_control.get("stop_requested") is not None:
27
+ thread_control["stop_requested"].value = 1
28
+
29
+ if thread_control.get("run_thread") is not None:
30
+ thread_control["run_thread"].join(timeout=5)
31
+ if thread_control["run_thread"].is_alive():
32
+ thread_control["run_thread"].terminate()
33
+ thread_control["run_thread"] = None
34
+
35
+ #@log_function_call
36
+ def run_classify_gui(q, fig_queue, stop_requested):
37
+ global vars_dict
38
+ process_stdout_stderr(q)
39
+ try:
40
+ settings = check_classify_gui_settings(vars_dict)
41
+ for key in settings:
42
+ value = settings[key]
43
+ print(key, value, type(value))
44
+ train_test_model_wrapper(settings['src'], settings)
45
+ except Exception as e:
46
+ q.put(f"Error during processing: {e}")
47
+ traceback.print_exc()
48
+ finally:
49
+ stop_requested.value = 1
50
+
51
+ #@log_function_call
52
+ def start_process(q, fig_queue):
53
+ global thread_control
54
+ if thread_control.get("run_thread") is not None:
55
+ initiate_abort()
56
+
57
+ stop_requested = Value('i', 0) # multiprocessing shared value for inter-process communication
58
+ thread_control["stop_requested"] = stop_requested
59
+ thread_control["run_thread"] = Process(target=run_classify_gui, args=(q, fig_queue, stop_requested))
60
+ thread_control["run_thread"].start()
61
+
62
+ def import_settings(scrollable_frame):
63
+ global vars_dict
64
+
65
+ csv_file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
66
+ csv_settings = read_settings_from_csv(csv_file_path)
67
+ variables = classify_variables()
68
+ new_settings = update_settings_from_csv(variables, csv_settings)
69
+ vars_dict = generate_fields(new_settings, scrollable_frame)
70
+
71
+ #@log_function_call
72
+ def initiate_classify_root(parent_frame):
73
+ global vars_dict, q, canvas, fig_queue, canvas_widget, thread_control
74
+
75
+ style = ttk.Style(parent_frame)
76
+ set_dark_style(style)
77
+ style_text_boxes(style)
78
+ set_default_font(parent_frame, font_name="Helvetica", size=8)
79
+
80
+ parent_frame.configure(bg='#333333')
81
+ parent_frame.grid_rowconfigure(0, weight=1)
82
+ parent_frame.grid_columnconfigure(0, weight=1)
83
+ fig_queue = Queue()
84
+
85
+ def _process_fig_queue():
86
+ global canvas
87
+ try:
88
+ while not fig_queue.empty():
89
+ clear_canvas(canvas)
90
+ fig = fig_queue.get_nowait()
91
+ for ax in fig.get_axes():
92
+ ax.set_xticks([]) # Remove x-axis ticks
93
+ ax.set_yticks([]) # Remove y-axis ticks
94
+ ax.xaxis.set_visible(False) # Hide the x-axis
95
+ ax.yaxis.set_visible(False) # Hide the y-axis
96
+ fig.tight_layout()
97
+ fig.set_facecolor('#333333')
98
+ canvas.figure = fig
99
+ fig_width, fig_height = canvas_widget.winfo_width(), canvas_widget.winfo_height()
100
+ fig.set_size_inches(fig_width / fig.dpi, fig_height / fig.dpi, forward=True)
101
+ canvas.draw_idle()
102
+ except Exception as e:
103
+ traceback.print_exc()
104
+ finally:
105
+ canvas_widget.after(100, _process_fig_queue)
106
+
107
+ def _process_console_queue():
108
+ while not q.empty():
109
+ message = q.get_nowait()
110
+ console_output.insert(tk.END, message)
111
+ console_output.see(tk.END)
112
+ console_output.after(100, _process_console_queue)
113
+
114
+ vertical_container = tk.PanedWindow(parent_frame, orient=tk.HORIZONTAL)
115
+ vertical_container.grid(row=0, column=0, sticky=tk.NSEW)
116
+ parent_frame.grid_rowconfigure(0, weight=1)
117
+ parent_frame.grid_columnconfigure(0, weight=1)
118
+
119
+ # Settings Section
120
+ settings_frame = tk.Frame(vertical_container, bg='#333333')
121
+ vertical_container.add(settings_frame, stretch="always")
122
+ settings_label = ttk.Label(settings_frame, text="Settings", background="#333333", foreground="white")
123
+ settings_label.grid(row=0, column=0, pady=10, padx=10)
124
+ scrollable_frame = ScrollableFrame(settings_frame, width=500)
125
+ scrollable_frame.grid(row=1, column=0, sticky="nsew")
126
+ settings_frame.grid_rowconfigure(1, weight=1)
127
+ settings_frame.grid_columnconfigure(0, weight=1)
128
+
129
+ # Setup for user input fields (variables)
130
+ variables = classify_variables()
131
+ vars_dict = generate_fields(variables, scrollable_frame)
132
+
133
+ # Button section
134
+ import_btn = CustomButton(scrollable_frame.scrollable_frame, text="Import", command=lambda: import_settings(scrollable_frame), font=('Helvetica', 10))
135
+ import_btn.grid(row=47, column=0, pady=20, padx=20)
136
+ run_button = CustomButton(scrollable_frame.scrollable_frame, text="Run", command=lambda: start_process(q, fig_queue), font=('Helvetica', 10))
137
+ run_button.grid(row=45, column=0, pady=20, padx=20)
138
+ abort_button = CustomButton(scrollable_frame.scrollable_frame, text="Abort", command=initiate_abort, font=('Helvetica', 10))
139
+ abort_button.grid(row=45, column=1, pady=20, padx=20)
140
+ progress_label = ttk.Label(scrollable_frame.scrollable_frame, text="Processing: 0%", background="black", foreground="white") # Create progress field
141
+ progress_label.grid(row=50, column=0, columnspan=2, sticky="ew", pady=(5, 0), padx=10)
142
+
143
+ # Plot Canvas Section
144
+ plot_frame = tk.PanedWindow(vertical_container, orient=tk.VERTICAL)
145
+ vertical_container.add(plot_frame, stretch="always")
146
+ figure = Figure(figsize=(30, 4), dpi=100, facecolor='#333333')
147
+ plot = figure.add_subplot(111)
148
+ plot.plot([], [])
149
+ plot.axis('off')
150
+ canvas = FigureCanvasTkAgg(figure, master=plot_frame)
151
+ canvas.get_tk_widget().configure(cursor='arrow', background='#333333', highlightthickness=0)
152
+ canvas_widget = canvas.get_tk_widget()
153
+ plot_frame.add(canvas_widget, stretch="always")
154
+ canvas.draw()
155
+ canvas.figure = figure
156
+
157
+ # Console Section
158
+ console_frame = tk.Frame(vertical_container, bg='#333333')
159
+ vertical_container.add(console_frame, stretch="always")
160
+ console_label = ttk.Label(console_frame, text="Console", background="#333333", foreground="white")
161
+ console_label.grid(row=0, column=0, pady=10, padx=10)
162
+ console_output = scrolledtext.ScrolledText(console_frame, height=10, bg='#333333', fg='white', insertbackground='white')
163
+ console_output.grid(row=1, column=0, sticky="nsew")
164
+ console_frame.grid_rowconfigure(1, weight=1)
165
+ console_frame.grid_columnconfigure(0, weight=1)
166
+
167
+ q = Queue()
168
+ sys.stdout = StdoutRedirector(console_output)
169
+ sys.stderr = StdoutRedirector(console_output)
170
+
171
+ _process_console_queue()
172
+ _process_fig_queue()
173
+
174
+ parent_frame.after(100, lambda: main_thread_update_function(parent_frame, q, fig_queue, canvas_widget, progress_label))
175
+
176
+ return parent_frame, vars_dict
177
+
178
+ def gui_classify():
179
+ root = tk.Tk()
180
+ width = root.winfo_screenwidth()
181
+ height = root.winfo_screenheight()
182
+ root.geometry(f"{width}x{height}")
183
+ root.title("SpaCr: classify objects")
184
+
185
+ # Clear previous content if any
186
+ if hasattr(root, 'content_frame'):
187
+ for widget in root.content_frame.winfo_children():
188
+ widget.destroy()
189
+ root.content_frame.grid_forget()
190
+ else:
191
+ root.content_frame = tk.Frame(root)
192
+ root.content_frame.grid(row=1, column=0, sticky="nsew")
193
+ root.grid_rowconfigure(1, weight=1)
194
+ root.grid_columnconfigure(0, weight=1)
195
+
196
+ initiate_classify_root(root.content_frame)
197
+ create_menu_bar(root)
198
+ root.mainloop()
199
+
200
+ if __name__ == "__main__":
201
+ gui_classify()
spacr/gui.py CHANGED
@@ -9,10 +9,9 @@ import requests
9
9
  from .gui_mask_app import initiate_mask_root
10
10
  from .gui_measure_app import initiate_measure_root
11
11
  from .annotate_app import initiate_annotation_app_root
12
- from .mask_app import initiate_mask_app_root
12
+ from .gui_make_masks_app import initiate_mask_app_root
13
13
  from .gui_classify_app import initiate_classify_root
14
-
15
- from .gui_utils import CustomButton, style_text_boxes
14
+ from .gui_utils import CustomButton, style_text_boxes, create_menu_bar
16
15
 
17
16
  class MainApp(tk.Tk):
18
17
  def __init__(self):
@@ -38,18 +37,24 @@ class MainApp(tk.Tk):
38
37
 
39
38
  def create_widgets(self):
40
39
  # Create the menu bar
41
- #create_menu_bar(self)
40
+ self.gui_create_menu_bar()
41
+
42
42
  # Create a canvas to hold the selected app and other elements
43
- self.canvas = tk.Canvas(self, bg="black", highlightthickness=0, width=4000, height=4000)
43
+ self.canvas = tk.Canvas(self, bg="black", highlightthickness=0)
44
44
  self.canvas.grid(row=0, column=0, sticky="nsew")
45
45
  self.grid_rowconfigure(0, weight=1)
46
46
  self.grid_columnconfigure(0, weight=1)
47
+
47
48
  # Create a frame inside the canvas to hold the main content
48
49
  self.content_frame = tk.Frame(self.canvas, bg="black")
49
50
  self.content_frame.pack(fill=tk.BOTH, expand=True)
51
+
50
52
  # Create startup screen with buttons for each GUI app
51
53
  self.create_startup_screen()
52
54
 
55
+ def gui_create_menu_bar(self):
56
+ create_menu_bar(self)
57
+
53
58
  def create_startup_screen(self):
54
59
  self.clear_frame(self.content_frame)
55
60
 
@@ -59,10 +64,10 @@ class MainApp(tk.Tk):
59
64
 
60
65
  # Load the logo image
61
66
  if not self.load_logo(logo_frame):
62
- tk.Label(logo_frame, text="Logo not found", bg="black", fg="white", font=('Arial', 24, tkFont.NORMAL)).pack(padx=10, pady=10)
67
+ tk.Label(logo_frame, text="Logo not found", bg="black", fg="white", font=('Helvetica', 24)).pack(padx=10, pady=10)
63
68
 
64
69
  # Add SpaCr text below the logo with padding for sharper text
65
- tk.Label(logo_frame, text="SpaCr", bg="black", fg="#008080", font=('Arial', 24, tkFont.NORMAL)).pack(padx=10, pady=10)
70
+ tk.Label(logo_frame, text="SpaCr", bg="black", fg="#008080", font=('Helvetica', 24)).pack(padx=10, pady=10)
66
71
 
67
72
  # Create a frame for the buttons and descriptions
68
73
  buttons_frame = tk.Frame(self.content_frame, bg="black")
@@ -72,10 +77,10 @@ class MainApp(tk.Tk):
72
77
  app_func, app_desc = app_data
73
78
 
74
79
  # Create custom button with text
75
- button = CustomButton(buttons_frame, text=app_name, command=lambda app_name=app_name: self.load_app(app_name))
80
+ button = CustomButton(buttons_frame, text=app_name, command=lambda app_name=app_name: self.load_app(app_name, app_func), font=('Helvetica', 12))
76
81
  button.grid(row=i, column=0, pady=10, padx=10, sticky="w")
77
82
 
78
- description_label = tk.Label(buttons_frame, text=app_desc, bg="black", fg="white", wraplength=800, justify="left", font=('Arial', 10, tkFont.NORMAL))
83
+ description_label = tk.Label(buttons_frame, text=app_desc, bg="black", fg="white", wraplength=800, justify="left", font=('Helvetica', 12))
79
84
  description_label.grid(row=i, column=1, pady=10, padx=10, sticky="w")
80
85
 
81
86
  # Ensure buttons have a fixed width
@@ -125,13 +130,14 @@ class MainApp(tk.Tk):
125
130
  print(f"An error occurred while processing the logo image: {e}")
126
131
  return False
127
132
 
128
- def load_app(self, app_name):
129
- selected_app_func, _ = self.gui_apps[app_name]
133
+ def load_app(self, app_name, app_func):
134
+ # Clear the current content frame
130
135
  self.clear_frame(self.content_frame)
131
136
 
137
+ # Initialize the selected app
132
138
  app_frame = tk.Frame(self.content_frame, bg="black")
133
139
  app_frame.pack(fill=tk.BOTH, expand=True)
134
- selected_app_func(app_frame, self.winfo_width(), self.winfo_height())
140
+ app_func(app_frame)
135
141
 
136
142
  def clear_frame(self, frame):
137
143
  for widget in frame.winfo_children():
@@ -142,4 +148,4 @@ def gui_app():
142
148
  app.mainloop()
143
149
 
144
150
  if __name__ == "__main__":
145
- gui_app()
151
+ gui_app()
spacr/gui_2.py CHANGED
@@ -1,52 +1,93 @@
1
- import customtkinter as ctk
1
+ import tkinter as tk
2
+ from tkinter import ttk
3
+ from tkinter import font as tkFont
2
4
  from PIL import Image, ImageTk
3
5
  import os
4
6
  import requests
5
7
 
6
- class MainApp(ctk.CTk):
8
+ # Import your GUI apps
9
+ from .gui_mask_app import initiate_mask_root
10
+ from .gui_measure_app import initiate_measure_root
11
+ from .annotate_app import initiate_annotation_app_root
12
+ from .mask_app import initiate_mask_app_root
13
+ from .gui_classify_app import initiate_classify_root
14
+
15
+ from .gui_utils import CustomButton, style_text_boxes
16
+
17
+ class MainApp(tk.Tk):
7
18
  def __init__(self):
8
19
  super().__init__()
9
20
  self.title("SpaCr GUI Collection")
10
- self.geometry("1200x800")
11
- ctk.set_appearance_mode("dark") # Modes: "System" (standard), "Dark", "Light"
12
- ctk.set_default_color_theme("dark-blue") # Themes: "blue" (standard), "green", "dark-blue")
13
-
14
- # Set scaling factor for high DPI displays; use a floating-point value.
15
- self.tk.call('tk', 'scaling', 1.5)
16
-
21
+ self.geometry("1100x1500")
22
+ self.configure(bg="black")
23
+ #self.attributes('-fullscreen', True)
24
+
25
+ style = ttk.Style()
26
+ style_text_boxes(style)
27
+
28
+ self.gui_apps = {
29
+ "Mask": (initiate_mask_root, "Generate cellpose masks for cells, nuclei and pathogen images."),
30
+ "Measure": (initiate_measure_root, "Measure single object intensity and morphological feature. Crop and save single object image"),
31
+ "Annotate": (initiate_annotation_app_root, "Annotation single object images on a grid. Annotations are saved to database."),
32
+ "Make Masks": (initiate_mask_app_root, "Adjust pre-existing Cellpose models to your specific dataset for improved performance"),
33
+ "Classify": (initiate_classify_root, "Train Torch Convolutional Neural Networks (CNNs) or Transformers to classify single object images.")
34
+ }
35
+
36
+ self.selected_app = tk.StringVar()
17
37
  self.create_widgets()
18
38
 
19
39
  def create_widgets(self):
20
- self.content_frame = ctk.CTkFrame(self)
21
- self.content_frame.pack(fill="both", expand=True, padx=20, pady=20)
40
+ # Create the menu bar
41
+ #create_menu_bar(self)
42
+ # Create a canvas to hold the selected app and other elements
43
+ self.canvas = tk.Canvas(self, bg="black", highlightthickness=0, width=4000, height=4000)
44
+ self.canvas.grid(row=0, column=0, sticky="nsew")
45
+ self.grid_rowconfigure(0, weight=1)
46
+ self.grid_columnconfigure(0, weight=1)
47
+ # Create a frame inside the canvas to hold the main content
48
+ self.content_frame = tk.Frame(self.canvas, bg="black")
49
+ self.content_frame.pack(fill=tk.BOTH, expand=True)
50
+ # Create startup screen with buttons for each GUI app
51
+ self.create_startup_screen()
22
52
 
23
- logo_frame = ctk.CTkFrame(self.content_frame)
53
+ def create_startup_screen(self):
54
+ self.clear_frame(self.content_frame)
55
+
56
+ # Create a frame for the logo and description
57
+ logo_frame = tk.Frame(self.content_frame, bg="black")
24
58
  logo_frame.pack(pady=20, expand=True)
25
59
 
60
+ # Load the logo image
26
61
  if not self.load_logo(logo_frame):
27
- ctk.CTkLabel(logo_frame, text="Logo not found", text_color="white", font=('Helvetica', 24)).pack(padx=10, pady=10)
28
-
29
- ctk.CTkLabel(logo_frame, text="SpaCr", text_color="#00BFFF", font=('Helvetica', 36, "bold")).pack(padx=10, pady=10)
30
-
31
- button = ctk.CTkButton(
32
- self.content_frame,
33
- text="Mask",
34
- command=self.load_mask_app,
35
- width=250,
36
- height=60,
37
- corner_radius=20,
38
- fg_color="#1E90FF",
39
- hover_color="#4682B4",
40
- text_color="white",
41
- font=("Helvetica", 18, "bold")
42
- )
43
- button.pack(pady=20)
62
+ tk.Label(logo_frame, text="Logo not found", bg="black", fg="white", font=('Helvetica', 24)).pack(padx=10, pady=10)
63
+
64
+ # Add SpaCr text below the logo with padding for sharper text
65
+ tk.Label(logo_frame, text="SpaCr", bg="black", fg="#008080", font=('Helvetica', 24)).pack(padx=10, pady=10)
66
+
67
+ # Create a frame for the buttons and descriptions
68
+ buttons_frame = tk.Frame(self.content_frame, bg="black")
69
+ buttons_frame.pack(pady=10, expand=True, padx=10)
70
+
71
+ for i, (app_name, app_data) in enumerate(self.gui_apps.items()):
72
+ app_func, app_desc = app_data
73
+
74
+ # Create custom button with text
75
+ button = CustomButton(buttons_frame, text=app_name, command=lambda app_name=app_name: self.load_app(app_name, app_func), font=('Helvetica', 12))
76
+ button.grid(row=i, column=0, pady=10, padx=10, sticky="w")
77
+
78
+ description_label = tk.Label(buttons_frame, text=app_desc, bg="black", fg="white", wraplength=800, justify="left", font=('Helvetica', 12))
79
+ description_label.grid(row=i, column=1, pady=10, padx=10, sticky="w")
80
+
81
+ # Ensure buttons have a fixed width
82
+ buttons_frame.grid_columnconfigure(0, minsize=150)
83
+ # Ensure descriptions expand as needed
84
+ buttons_frame.grid_columnconfigure(1, weight=1)
44
85
 
45
86
  def load_logo(self, frame):
46
87
  def download_image(url, save_path):
47
88
  try:
48
89
  response = requests.get(url, stream=True)
49
- response.raise_for_status()
90
+ response.raise_for_status() # Raise an HTTPError for bad responses
50
91
  with open(save_path, 'wb') as f:
51
92
  for chunk in response.iter_content(chunk_size=8192):
52
93
  f.write(chunk)
@@ -57,34 +98,63 @@ class MainApp(ctk.CTk):
57
98
 
58
99
  try:
59
100
  img_path = os.path.join(os.path.dirname(__file__), 'logo_spacr.png')
101
+ print(f"Trying to load logo from {img_path}")
60
102
  logo_image = Image.open(img_path)
61
103
  except (FileNotFoundError, Image.UnidentifiedImageError):
104
+ print(f"File {img_path} not found or is not a valid image. Attempting to download from GitHub.")
62
105
  if download_image('https://raw.githubusercontent.com/EinarOlafsson/spacr/main/spacr/logo_spacr.png', img_path):
63
106
  try:
107
+ print(f"Downloaded file size: {os.path.getsize(img_path)} bytes")
64
108
  logo_image = Image.open(img_path)
65
109
  except Image.UnidentifiedImageError as e:
110
+ print(f"Downloaded file is not a valid image: {e}")
66
111
  return False
67
112
  else:
68
113
  return False
69
114
  except Exception as e:
115
+ print(f"An error occurred while loading the logo: {e}")
70
116
  return False
71
-
72
117
  try:
73
- logo_image = logo_image.resize((200, 200), Image.Resampling.LANCZOS)
118
+ logo_image = logo_image.resize((800, 800), Image.Resampling.LANCZOS)
74
119
  logo_photo = ImageTk.PhotoImage(logo_image)
75
- logo_label = ctk.CTkLabel(frame, image=logo_photo)
120
+ logo_label = tk.Label(frame, image=logo_photo, bg="black")
76
121
  logo_label.image = logo_photo # Keep a reference to avoid garbage collection
77
122
  logo_label.pack()
78
123
  return True
79
124
  except Exception as e:
125
+ print(f"An error occurred while processing the logo image: {e}")
80
126
  return False
81
127
 
82
- def load_mask_app(self):
83
- print("Mask app loaded.") # Placeholder for mask app loading function
128
+ def load_app_v1(self, app_name):
129
+ selected_app_func, _ = self.gui_apps[app_name]
130
+ self.clear_frame(self.content_frame)
131
+
132
+ app_frame = tk.Frame(self.content_frame, bg="black")
133
+ app_frame.pack(fill=tk.BOTH, expand=True)
134
+ selected_app_func(app_frame)
135
+
136
+ def load_app(root, app_name, app_func):
137
+ if hasattr(root, 'current_app_id'):
138
+ root.after_cancel(root.current_app_id)
139
+ root.current_app_id = None
140
+
141
+ # Clear the current content frame
142
+ for widget in root.content_frame.winfo_children():
143
+ widget.destroy()
144
+
145
+ # Initialize the selected app
146
+ app_frame = tk.Frame(root.content_frame, bg="black")
147
+ app_frame.pack(fill=tk.BOTH, expand=True)
148
+ app_func(app_frame)
149
+
150
+ def clear_frame(self, frame):
151
+ for widget in frame.winfo_children():
152
+ widget.destroy()
153
+
84
154
 
85
155
  def gui_app():
86
156
  app = MainApp()
87
157
  app.mainloop()
88
158
 
89
159
  if __name__ == "__main__":
90
- gui_app()
160
+ gui_app()