SHARE
    TWEET
    Najeebsk

    GENRATE-AI-DATA.pyw

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

    AltStyle によって変換されたページ (->オリジナル) /