Advertisement
Najeebsk

AI-GENERATE2.pyw

May 30th, 2024 (edited)
850
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.72 KB | None | 0 0
  1. import os
  2. import numpy as np
  3. import imageio.v2 as imageio
  4. import tkinter as tk
  5. from tkinter import filedialog, ttk
  6. from PIL import Image, ImageTk
  7. import rarfile
  8.  
  9. header_len = 4 * 8  # uint32 bit length
  10.  
  11. def read_image(img_path):
  12.     img = np.array(imageio.imread(img_path), dtype=np.uint8)
  13.     orig_shape = img.shape
  14.     return img.flatten(), orig_shape
  15.  
  16. def decode_data(encoded_data):
  17.     out_mask = np.ones_like(encoded_data)
  18.     output = np.bitwise_and(encoded_data, out_mask)
  19.     return output
  20.  
  21. def write_file(file_path, file_bit_array):
  22.     bytes_data = np.packbits(file_bit_array)
  23.     with open(file_path, 'wb') as f:
  24.         f.write(bytes_data)
  25.  
  26. def browse_rar_file():
  27.     filename = filedialog.askopenfilename(initialdir="/", title="Select RAR File", filetypes=[("RAR files", "*.rar")])
  28.     if filename:
  29.         rar_entry.delete(0, tk.END)
  30.         rar_entry.insert(0, filename)
  31.         load_rar_file_images(filename)
  32.  
  33. def load_rar_file_images(filename):
  34.     try:
  35.         with rarfile.RarFile(filename) as rf:
  36.             rf.setpassword(password_entry.get())  # Set the password for the RAR file
  37.             file_list = rf.namelist()
  38.             image_files = sorted([file for file in file_list if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))])
  39.             image_dropdown['values'] = image_files
  40.             if image_files:
  41.                 image_dropdown.current(0)
  42.                 show_image_from_rar(filename, image_files[0])
  43.     except Exception as e:
  44.         print(f"Failed to read RAR file: {e}")
  45.  
  46. def show_image_from_rar(filename, image_name):
  47.     try:
  48.         with rarfile.RarFile(filename) as rf:
  49.             rf.setpassword(password_entry.get())  # Set the password for the RAR file
  50.             rf.extract(image_name, path="TEMP_DATA")
  51.             extracted_image_path = os.path.join("TEMP_DATA", image_name)
  52.             show_original_image(extracted_image_path)
  53.     except Exception as e:
  54.         print(f"Failed to extract image from RAR file: {e}")
  55.  
  56. def show_original_image(filename):
  57.     global original_image
  58.     try:
  59.         original_image = Image.open(filename)
  60.         original_image.thumbnail((400, 400))  # Resize if needed
  61.         update_zoom_image()  # Show the image at the initial zoom level
  62.     except Exception as e:
  63.         print(f"Failed to open image file: {e}")
  64.  
  65. def browse_save_location():
  66.     save_location = filedialog.asksaveasfilename(initialdir="/", title="Select Save Location", defaultextension=".jpg")
  67.     if save_location:
  68.         save_entry_unhide.delete(0, tk.END)
  69.         save_entry_unhide.insert(0, save_location)
  70.  
  71. def unhide_images():
  72.     original_file = rar_entry.get()
  73.     selected_image = image_dropdown.get()
  74.     save_file = save_entry_unhide.get()
  75.     password = password_entry.get()
  76.     if not os.path.isfile(original_file):
  77.         print("RAR file does not exist")
  78.         return
  79.  
  80.     try:
  81.         # Extract the selected image from the RAR file
  82.         with rarfile.RarFile(original_file) as rf:
  83.             rf.setpassword(password)  # Set the password for the RAR file
  84.             rf.extract(selected_image, path="TEMP_DATA")
  85.         extracted_image_path = os.path.join("TEMP_DATA", selected_image)
  86.     except rarfile.BadRarFile:
  87.         print("Failed to extract RAR file. Possibly wrong password or corrupted file.")
  88.         return
  89.  
  90.     # Proceed with the image decoding process
  91.     encoded_data, shape_orig = read_image(extracted_image_path)
  92.     data = decode_data(encoded_data)
  93.     el_array = np.packbits(data[:header_len])
  94.     extracted_len = el_array.view(np.uint32)[0]
  95.     data = data[header_len:extracted_len + header_len]
  96.     write_file(save_file, data)
  97.     print("Image decoded and saved")
  98.  
  99.     # Simulate a progress bar effect
  100.     progress = 0
  101.     while progress <= 100:
  102.         progress += 1
  103.         unhide_progress_bar['value'] = progress
  104.         root.update_idletasks()
  105.         root.after(50)  # Adjust speed of progress bar
  106.  
  107.     # Load and display the saved image
  108.     if os.path.isfile(save_file):
  109.         try:
  110.             global saved_image
  111.             saved_image = Image.open(save_file)
  112.             saved_image.thumbnail((400, 400))  # Resize if needed
  113.             update_zoom_image_saved()  # Show the saved image at the initial zoom level
  114.         except Exception as e:
  115.             print(f"Failed to open saved image: {e}")
  116.  
  117. def clear_folder(folder_path):
  118.     try:
  119.         # List all files in the folder
  120.         files = os.listdir(folder_path)
  121.        
  122.         # Iterate through each file and delete it
  123.         for file in files:
  124.             file_path = os.path.join(folder_path, file)
  125.             if os.path.isfile(file_path):
  126.                 os.remove(file_path)
  127.        
  128.         print("Folder data cleared successfully.")
  129.     except Exception as e:
  130.         print(f"An error occurred: {e}")
  131.  
  132. def update_zoom_image():
  133.     try:
  134.         zoom_factor = zoom_slider.get()
  135.         width, height = original_image.size
  136.         new_size = (int(width * zoom_factor), int(height * zoom_factor))
  137.         zoomed_image = original_image.resize(new_size, Image.LANCZOS)
  138.         zoomed_photo = ImageTk.PhotoImage(zoomed_image)
  139.         lbl.config(image=zoomed_photo)
  140.         lbl.image = zoomed_photo
  141.        
  142.         # Update the scroll region of the canvas to the new size of the image
  143.         canvas.config(scrollregion=canvas.bbox(tk.ALL))
  144.     except Exception as e:
  145.         print(f"Failed to update zoom image: {e}")
  146.  
  147. def update_zoom_image_saved():
  148.     try:
  149.         zoom_factor = zoom_slider_saved.get()
  150.         width, height = saved_image.size
  151.         new_size = (int(width * zoom_factor), int(height * zoom_factor))
  152.         zoomed_image_saved = saved_image.resize(new_size, Image.LANCZOS)
  153.         zoomed_photo_saved = ImageTk.PhotoImage(zoomed_image_saved)
  154.         lbl2.config(image=zoomed_photo_saved)
  155.         lbl2.image = zoomed_photo_saved
  156.        
  157.         # Update the scroll region of the canvas to the new size of the image
  158.         canvas2.config(scrollregion=canvas2.bbox(tk.ALL))
  159.     except Exception as e:
  160.         print(f"Failed to update zoom image: {e}")
  161.  
  162. # Clear folder on startup
  163. folder_path = "TEMP_DATA"
  164. clear_folder(folder_path)
  165.  
  166. root = tk.Tk()
  167. root.geometry("1000x660")
  168. root.title("Najeeb Generate AI Images")
  169.  
  170. # Password Entry
  171. tk.Label(root, text="Password:").place(x=10, y=10)
  172. password_entry = tk.Entry(root, show="*")
  173. password_entry.place(x=80, y=10)
  174.  
  175. # Input for RAR File Selection
  176. tk.Label(root, text="Select RAR File:").place(x=260, y=10)
  177. rar_entry = tk.Entry(root)
  178. rar_entry.place(x=360, y=10)
  179. browse_rar_button = tk.Button(root, text="Browse", command=browse_rar_file)
  180. browse_rar_button.place(x=520, y=8)
  181.  
  182. # Dropdown for RAR file images
  183. tk.Label(root, text="Select Image from RAR:").place(x=600, y=10)
  184. image_dropdown = ttk.Combobox(root, state="readonly")
  185. image_dropdown.place(x=730, y=10)
  186. image_dropdown.bind("<<ComboboxSelected>>", lambda e: show_image_from_rar(rar_entry.get(), image_dropdown.get()))
  187.  
  188. # Input for Save Location
  189. tk.Label(root, text="Select Save Location:").place(x=10, y=50)
  190. save_entry_unhide = tk.Entry(root)
  191. save_entry_unhide.place(x=130, y=50)
  192. browse_save_button = tk.Button(root, text="Browse", command=browse_save_location)
  193. browse_save_button.place(x=280, y=48)
  194.  
  195. # Button to unhide images
  196. unhide_button = tk.Button(root, text="Generate AI Image", command=unhide_images, bg="#6699FF", fg="white")
  197. unhide_button.place(x=350, y=48)
  198.  
  199. # Button to Temp-Data Clear
  200. clear_button = tk.Button(root, text="Clear Data", command=lambda: clear_folder("TEMP_DATA"), bg="#6699FF", fg="white")
  201. clear_button.place(x=480, y=48)
  202.  
  203. # Zoom Slider
  204. tk.Label(root, text="Zoom Image:").place(x=560, y=50)
  205. zoom_slider = tk.Scale(root, from_=0.1, to=10, orient=tk.HORIZONTAL, label="", resolution=0.1, command=lambda e: update_zoom_image())
  206. zoom_slider.set(1)
  207. zoom_slider.place(x=650, y=38)
  208.  
  209. # Progress Bar
  210. unhide_progress_bar = ttk.Progressbar(root, orient='horizontal', mode='determinate')
  211. unhide_progress_bar.place(x=10, y=80, width=980)
  212.  
  213. # Frame for Original Image with Scrollbars
  214. frame_original = tk.Frame(root, bd=3, bg="#2c3e50", width=480, height=540, relief=tk.GROOVE)
  215. frame_original.place(x=5, y=110)
  216.  
  217. canvas = tk.Canvas(frame_original, bg="#2c3e50", width=470, height=520)
  218. scroll_y = tk.Scrollbar(frame_original, orient="vertical", command=canvas.yview)
  219. scroll_x = tk.Scrollbar(frame_original, orient="horizontal", command=canvas.xview)
  220.  
  221. canvas.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
  222.  
  223. scroll_y.pack(side="right", fill="y")
  224. scroll_x.pack(side="bottom", fill="x")
  225. canvas.pack(side="left", fill="both", expand=True)
  226.  
  227. lbl = tk.Label(canvas, bg="#2c3e50")
  228. canvas.create_window((0, 0), window=lbl, anchor="nw")
  229.  
  230. # Frame for Generated AI Image with Scrollbars
  231. frame_generated = tk.Frame(root, bd=3, width=480, height=540, relief=tk.GROOVE, bg="#34495e")
  232. frame_generated.place(x=505, y=110)
  233.  
  234. canvas2 = tk.Canvas(frame_generated, bg="#34495e", width=470, height=520)
  235. scroll_y2 = tk.Scrollbar(frame_generated, orient="vertical", command=canvas2.yview)
  236. scroll_x2 = tk.Scrollbar(frame_generated, orient="horizontal", command=canvas2.xview)
  237.  
  238. canvas2.configure(yscrollcommand=scroll_y2.set, xscrollcommand=scroll_x2.set)
  239.  
  240. scroll_y2.pack(side="right", fill="y")
  241. scroll_x2.pack(side="bottom", fill="x")
  242. canvas2.pack(side="left", fill="both", expand=True)
  243.  
  244. lbl2 = tk.Label(canvas2, bg="#34495e")
  245. canvas2.create_window((0, 0), window=lbl2, anchor="nw")
  246.  
  247.  
  248. # Zoom Slider for the saved image
  249. tk.Label(root, text="Zoom AI Image:").place(x=770, y=50)
  250. zoom_slider_saved = tk.Scale(root, from_=0.1, to=10, orient=tk.HORIZONTAL, label="", resolution=0.1, command=lambda e: update_zoom_image_saved())
  251. zoom_slider_saved.set(1)
  252. zoom_slider_saved.place(x=870, y=38)
  253.  
  254. root.mainloop()
  255.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement