· 10 months ago · Nov 18, 2024, 07:00 AM
1import os
2import sqlite3
3import numpy as np
4import tkinter as tk
5from tkinter import filedialog, messagebox
6from PIL import Image, ImageTk
7import io
8import re
9from imageio.v2 import imread
10
11# Constants
12current_db_path = "DEEPDATA.db"
13decode_ai_folder = "AI"
14os.makedirs(decode_ai_folder, exist_ok=True)
15
16# UI Colors
17BG_COLOR = "#2b2d42"
18BTN_COLOR = "#8d99ae"
19BTN_TEXT_COLOR = "#edf2f4"
20LISTBOX_BG = "#3d405b"
21LISTBOX_FG = "#edf2f4"
22HEADER_LEN = 4 * 8 # uint32 bit length for header
23
24# Database Operations
25def connect_db():
26 """Create and connect to the SQLite database."""
27 conn = sqlite3.connect(current_db_path)
28 cursor = conn.cursor()
29 cursor.execute("""
30 CREATE TABLE IF NOT EXISTS images (
31 id INTEGER PRIMARY KEY AUTOINCREMENT,
32 name TEXT UNIQUE,
33 image BLOB
34 )
35 """)
36 conn.commit()
37 conn.close()
38
39# Listbox and Display
40def alphanumeric_sort_key(item):
41 """Sort key that splits strings into numeric and non-numeric parts."""
42 return [int(text) if text.isdigit() else text.lower() for text in re.split('(\d+)', item)]
43
44def load_images_from_sources():
45 """Load images from both DecodeAI folder and DEEPDATA.db into the listbox, sorted alphanumerically."""
46 image_list.delete(0, tk.END)
47
48 images = []
49
50 # Load images from DecodeAI folder
51 for file_name in os.listdir(decode_ai_folder):
52 if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
53 images.append(file_name)
54
55 # Load images from DEEPDATA.db
56 conn = sqlite3.connect(current_db_path)
57 cursor = conn.cursor()
58 cursor.execute("SELECT name FROM images")
59 db_images = cursor.fetchall()
60 conn.close()
61
62 # Add database images to the list
63 for (file_name,) in db_images:
64 if file_name not in images: # Avoid duplicates
65 images.append(file_name)
66
67 # Sort images alphanumerically
68 images.sort(key=alphanumeric_sort_key)
69
70 # Populate the Listbox
71 for file_name in images:
72 image_list.insert(tk.END, file_name)
73
74def view_selected_image():
75 """Display the selected original image in the GUI, prioritizing DEEPDATA.db over DecodeAI folder."""
76 selected_image = image_list.get(tk.ACTIVE)
77 if not selected_image:
78 messagebox.showwarning("No Selection", "No image selected.")
79 return
80
81 # Try to load the image from the database
82 conn = sqlite3.connect(current_db_path)
83 cursor = conn.cursor()
84 cursor.execute("SELECT image FROM images WHERE name = ?", (selected_image,))
85 row = cursor.fetchone()
86 conn.close()
87
88 if row:
89 # If the image is found in the database
90 try:
91 image_data = row[0]
92 image = Image.open(io.BytesIO(image_data))
93 image.thumbnail((400, 400))
94 original_tk_image = ImageTk.PhotoImage(image)
95 original_label.config(image=original_tk_image)
96 original_label.image = original_tk_image
97 return
98 except Exception as e:
99 messagebox.showerror("Error", f"Could not display image from the database: {e}")
100
101 # If not in database, try to load from DecodeAI folder
102 original_path = os.path.join(decode_ai_folder, selected_image)
103 if os.path.exists(original_path):
104 try:
105 original_image = Image.open(original_path)
106 original_image.thumbnail((400, 400))
107 original_tk_image = ImageTk.PhotoImage(original_image)
108 original_label.config(image=original_tk_image)
109 original_label.image = original_tk_image
110 except Exception as e:
111 messagebox.showerror("Error", f"Could not display the image from folder: {e}")
112 else:
113 messagebox.showinfo("Image Not Found", "Image not found in either the database or the folder.")
114
115def save_selected_image():
116 """Save the selected image from the database to the DecodeAI folder in PNG format."""
117 selected_image = image_list.get(tk.ACTIVE)
118 if not selected_image:
119 messagebox.showwarning("No Selection", "No image selected.")
120 return
121
122 conn = sqlite3.connect(current_db_path)
123 cursor = conn.cursor()
124 cursor.execute("SELECT image FROM images WHERE name = ?", (selected_image,))
125 result = cursor.fetchone()
126 conn.close()
127
128 if result:
129 # Ensure the image name ends with .png for saving
130 save_file_name = f"{os.path.splitext(selected_image)[0]}.png"
131 save_path = os.path.join(decode_ai_folder, save_file_name)
132 try:
133 # Convert the BLOB data back to an image and save it
134 image_data = io.BytesIO(result[0])
135 image = Image.open(image_data)
136 image.save(save_path, format="PNG")
137 messagebox.showinfo("Saved", f"Image saved successfully to {save_path}")
138 except Exception as e:
139 messagebox.showerror("Error", f"Failed to save the image: {e}")
140 else:
141 messagebox.showwarning("Not Found", "Could not find the image data.")
142
143# New Functionality: Select Image from DB and Save to Folder
144def add_image():
145 """Add a new image to the database."""
146 filepath = filedialog.askopenfilename(
147 title="Select Image",
148 filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.bmp;*.gif")]
149 )
150 if not filepath:
151 return
152
153 name = os.path.basename(filepath)
154 with open(filepath, 'rb') as file:
155 image_data = file.read()
156
157 conn = sqlite3.connect(current_db_path)
158 cursor = conn.cursor()
159 try:
160 cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
161 conn.commit()
162 #load_images()
163 messagebox.showinfo("Success", f"Image '{name}' added successfully.")
164 except sqlite3.IntegrityError:
165 messagebox.showwarning("Duplicate", f"Image '{name}' already exists.")
166 finally:
167 conn.close()
168
169def delete_image():
170 """Delete the selected image."""
171 selected_image = image_list.get(tk.ACTIVE)
172 if not selected_image:
173 messagebox.showwarning("No Selection", "No image selected.")
174 return
175
176 conn = sqlite3.connect(current_db_path)
177 cursor = conn.cursor()
178 cursor.execute("DELETE FROM images WHERE name = ?", (selected_image,))
179 conn.commit()
180 conn.close()
181 #load_images()
182 messagebox.showinfo("Deleted", f"Image '{selected_image}' deleted successfully.")
183
184# Steganography Functions (Same as before)
185def read_image(img_path):
186 img = np.array(imread(img_path), dtype=np.uint8)
187 return img.flatten(), img.shape
188
189def decode_data(encoded_data):
190 return np.bitwise_and(encoded_data, np.ones_like(encoded_data))
191
192def write_file(file_path, file_bit_array):
193 bytes_data = np.packbits(file_bit_array)
194 with open(file_path, 'wb') as f:
195 f.write(bytes_data)
196
197def decode_hidden_image():
198 """Decode and display the hidden image."""
199 selected_image = image_list.get(tk.ACTIVE)
200 if not selected_image:
201 messagebox.showwarning("No Selection", "No image selected.")
202 return
203
204 encoded_image_path = os.path.join(decode_ai_folder, selected_image)
205 encoded_data, shape_orig = read_image(encoded_image_path)
206 data = decode_data(encoded_data)
207 el_array = np.packbits(data[:HEADER_LEN])
208 extracted_len = el_array.view(np.uint32)[0]
209 hidden_data = data[HEADER_LEN:HEADER_LEN + extracted_len]
210
211 # Save the decoded image
212 hidden_image_path = os.path.join(decode_ai_folder, f"decoded_{selected_image}")
213 write_file(hidden_image_path, hidden_data)
214
215 # Preview the decoded image
216 try:
217 decoded_image = Image.open(hidden_image_path)
218 decoded_image.thumbnail((400, 400))
219 decoded_tk_image = ImageTk.PhotoImage(decoded_image)
220 decoded_label.config(image=decoded_tk_image)
221 decoded_label.image = decoded_tk_image
222 messagebox.showinfo("Success", f"Hidden image saved and displayed from: {hidden_image_path}")
223 except Exception as e:
224 messagebox.showerror("Error", f"Failed to preview the decoded image: {e}")
225
226# Refresh List Function
227def refresh_list():
228 """Refresh the image list in the Listbox."""
229 load_images_from_sources()
230
231# Main GUI
232root = tk.Tk()
233root.title("Najeeb AI Images Generator")
234root.geometry("1000x700")
235root.configure(bg=BG_COLOR)
236
237connect_db()
238
239# Listbox Frame
240listbox_frame = tk.Frame(root, bg=BG_COLOR)
241listbox_frame.pack(side=tk.LEFT, padx=10, pady=10)
242
243scrollbar = tk.Scrollbar(listbox_frame, orient=tk.VERTICAL)
244scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
245
246image_list = tk.Listbox(listbox_frame, selectmode=tk.SINGLE, width=15, height=45, bg=LISTBOX_BG, fg=LISTBOX_FG, yscrollcommand=scrollbar.set)
247image_list.pack(side=tk.LEFT)
248scrollbar.config(command=image_list.yview)
249
250# Button Frame (All buttons in one row)
251button_frame = tk.Frame(root, bg=BG_COLOR)
252button_frame.pack(pady=10)
253
254view_button = tk.Button(button_frame, text="View Image", command=view_selected_image, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
255view_button.pack(side=tk.LEFT, padx=5)
256
257save_button = tk.Button(button_frame, text="Save Image", command=save_selected_image, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
258save_button.pack(side=tk.LEFT, padx=5)
259
260refresh_button = tk.Button(button_frame, text="Refresh List", command=refresh_list, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
261refresh_button.pack(side=tk.LEFT, padx=5)
262
263decode_button = tk.Button(button_frame, text="Decode Image", command=decode_hidden_image, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
264decode_button.pack(side=tk.LEFT, padx=5)
265
266# Add Button
267add_button = tk.Button(button_frame, text="Add Image", command=add_image, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
268add_button.pack(side=tk.LEFT, padx=5)
269
270# Delete Button
271delete_button= tk.Button(button_frame, text="Delete Image", command=delete_image, bg=BTN_COLOR, fg=BTN_TEXT_COLOR)
272delete_button.pack(side=tk.LEFT, padx=5)
273
274# Display Labels for Original and Decoded images side by side
275image_frame = tk.Frame(root, bg=BG_COLOR)
276image_frame.pack(pady=10)
277
278original_label = tk.Label(image_frame)
279original_label.pack(side=tk.LEFT, padx=10)
280
281decoded_label = tk.Label(image_frame)
282decoded_label.pack(side=tk.LEFT, padx=10)
283
284# Load images into Listbox
285load_images_from_sources()
286
287root.mainloop()
288