Project

General

Profile

Codes » History » Version 4

Zhi Jie YEW, 11/06/2025 02:48 PM

1 2 Anderson PHILLIP
[[Wiki|← Back to Start Page]]
2
3 1 Wing Sum TANG
h1. Codes
4 3 Zhi Jie YEW
5
gui.py
6 4 Zhi Jie YEW
<pre><code class="python">
7 3 Zhi Jie YEW
# gui.py
8
9
import tkinter as tk
10
from tkinter import ttk, filedialog, messagebox
11
import threading
12
import json
13
import os
14
15
# Import the logic classes
16
from main_alpha_blender import MainAlphaBlender
17
from video_processor import VideoProcessor
18
19
class BlenderGUI:
20
    """A Tkinter GUI with tabs for image and video edge blending."""
21
    def __init__(self, master):
22
        self.master = master
23
        master.title("Image and Video Edge Blender")
24
        master.geometry("600x450") # Increased height for new buttons
25
26
        # --- Create a Tabbed Interface ---
27
        self.notebook = ttk.Notebook(master)
28
        self.notebook.pack(pady=10, padx=10, fill="both", expand=True)
29
30
        self.image_tab = ttk.Frame(self.notebook, padding="10")
31
        self.video_tab = ttk.Frame(self.notebook, padding="10")
32
33
        self.notebook.add(self.image_tab, text="Image Blender")
34
        self.notebook.add(self.video_tab, text="Video Processor")
35
36
        # --- Populate each tab ---
37
        self.create_image_widgets()
38
        self.create_video_widgets()
39
40
        # --- NEW: Add a frame at the bottom for config management ---
41
        self.config_frame = ttk.Frame(master, padding=(10, 0, 10, 10))
42
        self.config_frame.pack(fill=tk.X, side=tk.BOTTOM)
43
        self.create_config_widgets()
44
45
        # --- NEW: Load default config on startup ---
46
        # It will silently fail if config.json doesn't exist, using hardcoded defaults.
47
        self.load_config(filepath="config.json", silent=True)
48
49
    def create_image_widgets(self):
50
        """Creates all widgets for the Image Blender tab."""
51
        self.image_blender = MainAlphaBlender()
52
        
53
        ttk.Label(self.image_tab, text="Input Image Directory:").grid(row=0, column=0, sticky=tk.W, pady=2)
54
        self.img_input_path_var = tk.StringVar(value=self.image_blender.image_path)
55
        ttk.Entry(self.image_tab, textvariable=self.img_input_path_var, width=50).grid(row=0, column=1, sticky=tk.EW, padx=5)
56
        ttk.Button(self.image_tab, text="Browse...", command=self.select_img_input_dir).grid(row=0, column=2)
57
58
        ttk.Label(self.image_tab, text="Output Directory:").grid(row=1, column=0, sticky=tk.W, pady=2)
59
        self.img_output_path_var = tk.StringVar(value=self.image_blender.output_dir)
60
        ttk.Entry(self.image_tab, textvariable=self.img_output_path_var, width=50).grid(row=1, column=1, sticky=tk.EW, padx=5)
61
        ttk.Button(self.image_tab, text="Browse...", command=self.select_img_output_dir).grid(row=1, column=2)
62
63
        ttk.Label(self.image_tab, text="Blend Width (pixels):").grid(row=2, column=0, sticky=tk.W, pady=5)
64
        self.img_blend_width_var = tk.IntVar(value=self.image_blender.blend_width)
65
        ttk.Entry(self.image_tab, textvariable=self.img_blend_width_var, width=10).grid(row=2, column=1, sticky=tk.W, padx=5)
66
67
        ttk.Label(self.image_tab, text="Gamma Value:").grid(row=3, column=0, sticky=tk.W, pady=2)
68
        self.img_gamma_var = tk.DoubleVar(value=self.image_blender.gamma_value)
69
        ttk.Entry(self.image_tab, textvariable=self.img_gamma_var, width=10).grid(row=3, column=1, sticky=tk.W, padx=5)
70
71
        ttk.Label(self.image_tab, text="Blend Method:").grid(row=4, column=0, sticky=tk.W, pady=2)
72
        self.img_method_var = tk.StringVar(value=self.image_blender.method)
73
        methods = ['linear', 'cosine', 'quadratic', 'sqrt', 'log', 'sigmoid']
74
        ttk.Combobox(self.image_tab, textvariable=self.img_method_var, values=methods, state="readonly").grid(row=4, column=1, sticky=tk.W, padx=5)
75
76
        self.img_preview_var = tk.BooleanVar(value=self.image_blender.preview)
77
        ttk.Checkbutton(self.image_tab, text="Show Preview After Processing", variable=self.img_preview_var).grid(row=5, column=1, sticky=tk.W, pady=10, padx=5)
78
79
        ttk.Button(self.image_tab, text="Run Blending Process", command=self.run_image_blending).grid(row=6, column=1, pady=20, sticky=tk.W)
80
81
        self.img_status_var = tk.StringVar(value="Ready.")
82
        ttk.Label(self.image_tab, textvariable=self.img_status_var, font=("Helvetica", 10, "italic")).grid(row=7, column=0, columnspan=3, sticky=tk.W, pady=5)
83
84
        self.image_tab.columnconfigure(1, weight=1)
85
86
    def create_video_widgets(self):
87
        """Creates all widgets for the Video Processor tab."""
88
        self.video_processor = VideoProcessor()
89
90
        ttk.Label(self.video_tab, text="Input Video File:").grid(row=0, column=0, sticky=tk.W, pady=2)
91
        self.vid_input_path_var = tk.StringVar()
92
        ttk.Entry(self.video_tab, textvariable=self.vid_input_path_var, width=50).grid(row=0, column=1, sticky=tk.EW, padx=5)
93
        ttk.Button(self.video_tab, text="Browse...", command=self.select_vid_input_file).grid(row=0, column=2)
94
95
        ttk.Label(self.video_tab, text="Output Directory:").grid(row=1, column=0, sticky=tk.W, pady=2)
96
        self.vid_output_path_var = tk.StringVar(value=self.video_processor.output_dir)
97
        ttk.Entry(self.video_tab, textvariable=self.vid_output_path_var, width=50).grid(row=1, column=1, sticky=tk.EW, padx=5)
98
        ttk.Button(self.video_tab, text="Browse...", command=self.select_vid_output_dir).grid(row=1, column=2)
99
100
        ttk.Label(self.video_tab, text="Blend Width (pixels):").grid(row=2, column=0, sticky=tk.W, pady=5)
101
        self.vid_blend_width_var = tk.IntVar(value=self.video_processor.blend_width)
102
        ttk.Entry(self.video_tab, textvariable=self.vid_blend_width_var, width=10).grid(row=2, column=1, sticky=tk.W, padx=5)
103
104
        ttk.Label(self.video_tab, text="Blend Method:").grid(row=3, column=0, sticky=tk.W, pady=2)
105
        self.vid_method_var = tk.StringVar(value=self.video_processor.blend_method)
106
        methods = ['linear', 'cosine']
107
        ttk.Combobox(self.video_tab, textvariable=self.vid_method_var, values=methods, state="readonly").grid(row=3, column=1, sticky=tk.W, padx=5)
108
109
        self.run_video_button = ttk.Button(self.video_tab, text="Process Video", command=self.run_video_processing_thread)
110
        self.run_video_button.grid(row=4, column=1, pady=20, sticky=tk.W)
111
112
        self.vid_status_var = tk.StringVar(value="Ready.")
113
        ttk.Label(self.video_tab, textvariable=self.vid_status_var).grid(row=5, column=0, columnspan=3, sticky=tk.W, pady=5)
114
        
115
        self.video_tab.columnconfigure(1, weight=1)
116
117
    def create_config_widgets(self):
118
        """Creates the Load and Save configuration buttons."""
119
        ttk.Button(self.config_frame, text="Load Config", command=self.load_config).pack(side=tk.LEFT, padx=5)
120
        ttk.Button(self.config_frame, text="Save Config", command=self.save_config).pack(side=tk.LEFT, padx=5)
121
122
    def load_config(self, filepath=None, silent=False):
123
        """Loads settings from a JSON file and updates the GUI."""
124
        if filepath is None:
125
            filepath = filedialog.askopenfilename(
126
                title="Open Configuration File",
127
                filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
128
            )
129
        
130
        if not filepath or not os.path.exists(filepath):
131
            if not silent:
132
                messagebox.showwarning("Load Config", "No configuration file selected or file not found.")
133
            return
134
135
        try:
136
            with open(filepath, 'r') as f:
137
                data = json.load(f)
138
139
            # Update Image Tab variables
140
            self.img_input_path_var.set(data.get("image_path", "OriginalImages"))
141
            self.img_output_path_var.set(data.get("output_dir", "Results"))
142
            self.img_blend_width_var.set(data.get("blend_width", 200))
143
            self.img_gamma_var.set(data.get("gamma_value", 1.4))
144
            self.img_method_var.set(data.get("blend_method", "cosine"))
145
            self.img_preview_var.set(data.get("preview", True))
146
147
            # Update Video Tab variables
148
            self.vid_input_path_var.set(data.get("video_input_path", ""))
149
            self.vid_output_path_var.set(data.get("video_output_dir", "VideoResults"))
150
            self.vid_blend_width_var.set(data.get("video_blend_width", 100))
151
            self.vid_method_var.set(data.get("video_blend_method", "linear"))
152
            
153
            if not silent:
154
                messagebox.showinfo("Load Config", f"Configuration loaded successfully from {os.path.basename(filepath)}.")
155
156
        except Exception as e:
157
            if not silent:
158
                messagebox.showerror("Load Config Error", f"Failed to load or parse the configuration file.\n\nError: {e}")
159
160
    def save_config(self):
161
        """Saves the current GUI settings to a JSON file."""
162
        filepath = filedialog.asksaveasfilename(
163
            title="Save Configuration File",
164
            defaultextension=".json",
165
            initialfile="config.json",
166
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
167
        )
168
169
        if not filepath:
170
            return
171
172
        try:
173
            config_data = {
174
                # Image Tab settings
175
                "image_path": self.img_input_path_var.get(),
176
                "output_dir": self.img_output_path_var.get(),
177
                "blend_width": self.img_blend_width_var.get(),
178
                "gamma_value": self.img_gamma_var.get(),
179
                "blend_method": self.img_method_var.get(),
180
                "preview": self.img_preview_var.get(),
181
                
182
                # Video Tab settings
183
                "video_input_path": self.vid_input_path_var.get(),
184
                "video_output_dir": self.vid_output_path_var.get(),
185
                "video_blend_width": self.vid_blend_width_var.get(),
186
                "video_blend_method": self.vid_method_var.get()
187
            }
188
189
            with open(filepath, 'w') as f:
190
                json.dump(config_data, f, indent=4)
191
            
192
            messagebox.showinfo("Save Config", f"Configuration saved successfully to {os.path.basename(filepath)}.")
193
194
        except Exception as e:
195
            messagebox.showerror("Save Config Error", f"Failed to save the configuration file.\n\nError: {e}")
196
197
    # --- Callbacks for Image Tab ---
198
    def select_img_input_dir(self):
199
        path = filedialog.askdirectory(title="Select Input Image Directory")
200
        if path: self.img_input_path_var.set(path)
201
202
    def select_img_output_dir(self):
203
        path = filedialog.askdirectory(title="Select Output Directory")
204
        if path: self.img_output_path_var.set(path)
205
206
    def run_image_blending(self):
207
        self.image_blender.image_path = self.img_input_path_var.get()
208
        self.image_blender.output_dir = self.img_output_path_var.get()
209
        self.image_blender.blend_width = self.img_blend_width_var.get()
210
        self.image_blender.gamma_value = self.img_gamma_var.get()
211
        self.image_blender.method = self.img_method_var.get()
212
        self.image_blender.preview = self.img_preview_var.get()
213
        self.image_blender.update_paths()
214
        
215
        success, message = self.image_blender.run()
216
        if success:
217
            self.img_status_var.set(f"Success! {message}")
218
            messagebox.showinfo("Success", message)
219
        else:
220
            self.img_status_var.set(f"Error: {message}")
221
            messagebox.showerror("Error", message)
222
223
    # --- Callbacks for Video Tab ---
224
    def select_vid_input_file(self):
225
        path = filedialog.askopenfilename(title="Select Input Video File", filetypes=[("MP4 files", "*.mp4"), ("All files", "*.*")])
226
        if path: self.vid_input_path_var.set(path)
227
228
    def select_vid_output_dir(self):
229
        path = filedialog.askdirectory(title="Select Output Directory")
230
        if path: self.vid_output_path_var.set(path)
231
232
    def update_video_status(self, message):
233
        """Thread-safe method to update the GUI status label."""
234
        self.vid_status_var.set(message)
235
236
    def run_video_processing_thread(self):
237
        """Starts the video processing in a new thread to avoid freezing the GUI."""
238
        self.run_video_button.config(state="disabled")
239
        thread = threading.Thread(target=self.run_video_processing)
240
        thread.daemon = True
241
        thread.start()
242
243
    def run_video_processing(self):
244
        """The actual processing logic, run in the background thread."""
245
        try:
246
            self.video_processor.input_video_path = self.vid_input_path_var.get()
247
            self.video_processor.output_dir = self.vid_output_path_var.get()
248
            self.video_processor.blend_width = self.vid_blend_width_var.get()
249
            self.video_processor.blend_method = self.vid_method_var.get()
250
251
            success, message = self.video_processor.run(status_callback=self.update_video_status)
252
253
            if success:
254
                messagebox.showinfo("Success", message)
255
            else:
256
                messagebox.showerror("Error", message)
257
258
        except Exception as e:
259
            messagebox.showerror("Critical Error", f"An unexpected error occurred: {e}")
260
        finally:
261
            self.run_video_button.config(state="normal")
262
</code></pre>