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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import json
|
| 4 |
+
import collections
|
| 5 |
+
import threading
|
| 6 |
+
import tkinter as tk
|
| 7 |
+
from tkinter import filedialog
|
| 8 |
+
from PIL import Image, ImageTk, PngImagePlugin
|
| 9 |
+
import customtkinter as ctk
|
| 10 |
+
from tkinterdnd2 import TkinterDnD, DND_FILES
|
| 11 |
+
|
| 12 |
+
# 設定主題
|
| 13 |
+
ctk.set_appearance_mode("Dark")
|
| 14 |
+
ctk.set_default_color_theme("blue")
|
| 15 |
+
|
| 16 |
+
# 防止 PIL 截斷過長的 Metadata
|
| 17 |
+
PngImagePlugin.MAX_TEXT_CHUNK = 5 * 1024 * 1024
|
| 18 |
+
|
| 19 |
+
class ImageViewer(ctk.CTkToplevel):
|
| 20 |
+
"""獨立視窗:圖片檢視器"""
|
| 21 |
+
def __init__(self, parent, image_path, prompt_text):
|
| 22 |
+
super().__init__(parent)
|
| 23 |
+
self.title("圖片檢視器 - 僅顯示正向 Prompt")
|
| 24 |
+
self.geometry("900x750")
|
| 25 |
+
self.attributes("-topmost", True)
|
| 26 |
+
|
| 27 |
+
self.img_frame = ctk.CTkFrame(self)
|
| 28 |
+
self.img_frame.pack(fill="both", expand=True, padx=10, pady=10)
|
| 29 |
+
|
| 30 |
+
self.img_label = ctk.CTkLabel(self.img_frame, text="讀取中...")
|
| 31 |
+
self.img_label.pack(fill="both", expand=True)
|
| 32 |
+
|
| 33 |
+
self._load_image(image_path)
|
| 34 |
+
|
| 35 |
+
# 底部 Prompt 資訊區
|
| 36 |
+
self.info_frame = ctk.CTkFrame(self, height=150)
|
| 37 |
+
self.info_frame.pack(fill="x", padx=10, pady=(0, 10))
|
| 38 |
+
|
| 39 |
+
ctk.CTkLabel(self.info_frame, text="正向 Prompt:", font=("Arial", 12, "bold")).pack(anchor="w", padx=5, pady=5)
|
| 40 |
+
|
| 41 |
+
self.prompt_box = ctk.CTkTextbox(self.info_frame, height=120)
|
| 42 |
+
self.prompt_box.pack(fill="x", padx=5, pady=5)
|
| 43 |
+
self.prompt_box.insert("1.0", prompt_text)
|
| 44 |
+
self.prompt_box.configure(state="disabled")
|
| 45 |
+
|
| 46 |
+
def _load_image(self, path):
|
| 47 |
+
try:
|
| 48 |
+
pil_img = Image.open(path)
|
| 49 |
+
base_height = 550
|
| 50 |
+
w_percent = (base_height / float(pil_img.size[1]))
|
| 51 |
+
w_size = int((float(pil_img.size[0]) * float(w_percent)))
|
| 52 |
+
|
| 53 |
+
pil_img = pil_img.resize((w_size, base_height), Image.Resampling.LANCZOS)
|
| 54 |
+
self.ctk_img = ctk.CTkImage(light_image=pil_img, dark_image=pil_img, size=(w_size, base_height))
|
| 55 |
+
self.img_label.configure(image=self.ctk_img, text="")
|
| 56 |
+
except Exception as e:
|
| 57 |
+
self.img_label.configure(text=f"圖片載入失敗: {e}")
|
| 58 |
+
|
| 59 |
+
class AIImageManagerV5(ctk.CTk, TkinterDnD.DnDWrapper):
|
| 60 |
+
def __init__(self, *args, **kwargs):
|
| 61 |
+
super().__init__(*args, **kwargs)
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
self.TkdndVersion = TkinterDnD._require(self)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"DnD Error: {e}")
|
| 67 |
+
|
| 68 |
+
self.title("AI 圖庫管理器 v5.0 - 專注正向 Prompt")
|
| 69 |
+
self.geometry("1280x850")
|
| 70 |
+
|
| 71 |
+
self.image_index = []
|
| 72 |
+
self.prompt_counts = collections.Counter()
|
| 73 |
+
|
| 74 |
+
self.context_menu = tk.Menu(self, tearoff=0)
|
| 75 |
+
self.context_menu.add_command(label="📥 另存圖片", command=self._download_current_image)
|
| 76 |
+
self.selected_image_path = None
|
| 77 |
+
|
| 78 |
+
self._setup_ui()
|
| 79 |
+
|
| 80 |
+
def _setup_ui(self):
|
| 81 |
+
self.grid_columnconfigure(1, weight=1)
|
| 82 |
+
self.grid_rowconfigure(0, weight=1)
|
| 83 |
+
|
| 84 |
+
# === 左側側邊欄 ===
|
| 85 |
+
self.sidebar = ctk.CTkFrame(self, width=300, corner_radius=0)
|
| 86 |
+
self.sidebar.grid(row=0, column=0, sticky="nsew")
|
| 87 |
+
self.sidebar.grid_rowconfigure(4, weight=1)
|
| 88 |
+
|
| 89 |
+
self.drop_label = ctk.CTkLabel(self.sidebar, text="📂 拖放資料夾至此",
|
| 90 |
+
fg_color="gray25", corner_radius=8, height=80)
|
| 91 |
+
self.drop_label.grid(row=0, column=0, padx=10, pady=(20, 10), sticky="ew")
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
self.drop_label.drop_target_register(DND_FILES)
|
| 95 |
+
self.drop_label.dnd_bind('<<Drop>>', self._on_folder_drop)
|
| 96 |
+
except: pass
|
| 97 |
+
|
| 98 |
+
self.search_var = ctk.StringVar()
|
| 99 |
+
self.search_var.trace("w", self._on_search_change)
|
| 100 |
+
ctk.CTkEntry(self.sidebar, placeholder_text="🔍 搜尋正向關鍵字...", textvariable=self.search_var)\
|
| 101 |
+
.grid(row=1, column=0, padx=10, pady=10, sticky="ew")
|
| 102 |
+
|
| 103 |
+
# 統計設定
|
| 104 |
+
ctrl_frame = ctk.CTkFrame(self.sidebar, fg_color="transparent")
|
| 105 |
+
ctrl_frame.grid(row=2, column=0, padx=10, pady=5, sticky="ew")
|
| 106 |
+
|
| 107 |
+
ctk.CTkLabel(ctrl_frame, text="熱門標籤:", font=("Arial", 14, "bold")).pack(side="left")
|
| 108 |
+
|
| 109 |
+
self.top_k_var = ctk.StringVar(value="20")
|
| 110 |
+
self.top_k_menu = ctk.CTkOptionMenu(ctrl_frame, values=["20", "50", "100"],
|
| 111 |
+
variable=self.top_k_var, width=80,
|
| 112 |
+
command=self._update_stats_limit)
|
| 113 |
+
self.top_k_menu.pack(side="right")
|
| 114 |
+
|
| 115 |
+
self.stats_scroll = ctk.CTkScrollableFrame(self.sidebar, label_text="")
|
| 116 |
+
self.stats_scroll.grid(row=4, column=0, padx=10, pady=10, sticky="nsew")
|
| 117 |
+
|
| 118 |
+
# === 右側預覽區 ===
|
| 119 |
+
self.gallery_frame = ctk.CTkScrollableFrame(self, label_text="圖片預覽區")
|
| 120 |
+
self.gallery_frame.grid(row=0, column=1, padx=20, pady=20, sticky="nsew")
|
| 121 |
+
|
| 122 |
+
# --- 核心邏輯修改區 ---
|
| 123 |
+
|
| 124 |
+
def _clean_a1111_prompt(self, raw_text):
|
| 125 |
+
"""
|
| 126 |
+
過濾器:只保留 Negative prompt 之前的內容
|
| 127 |
+
"""
|
| 128 |
+
if not raw_text: return ""
|
| 129 |
+
|
| 130 |
+
# 關鍵邏輯:一旦出現 Negative prompt,切斷後面所有內容
|
| 131 |
+
if "Negative prompt:" in raw_text:
|
| 132 |
+
cleaned = raw_text.split("Negative prompt:")[0]
|
| 133 |
+
else:
|
| 134 |
+
cleaned = raw_text
|
| 135 |
+
|
| 136 |
+
# 額外清理:有時候 A1111 就算沒有 Negative prompt,也會有 Steps: 等資訊
|
| 137 |
+
# 如果您希望連 Steps 資訊都不要,可以再加一行:
|
| 138 |
+
# if "Steps:" in cleaned: cleaned = cleaned.split("Steps:")[0]
|
| 139 |
+
|
| 140 |
+
return cleaned.strip()
|
| 141 |
+
|
| 142 |
+
def _extract_metadata(self, img_path):
|
| 143 |
+
"""讀取並清理 Metadata"""
|
| 144 |
+
raw_data = ""
|
| 145 |
+
|
| 146 |
+
# 1. 嘗試讀取同名 txt
|
| 147 |
+
txt_path = os.path.splitext(img_path)[0] + ".txt"
|
| 148 |
+
if os.path.exists(txt_path):
|
| 149 |
+
try:
|
| 150 |
+
with open(txt_path, 'r', encoding='utf-8') as tf:
|
| 151 |
+
raw_data = tf.read().strip()
|
| 152 |
+
except: pass
|
| 153 |
+
|
| 154 |
+
# 2. 如果 txt 沒東西,讀 PNG
|
| 155 |
+
if not raw_data:
|
| 156 |
+
try:
|
| 157 |
+
img = Image.open(img_path)
|
| 158 |
+
info = img.info or {}
|
| 159 |
+
|
| 160 |
+
# A1111
|
| 161 |
+
if 'parameters' in info:
|
| 162 |
+
raw_data = info['parameters']
|
| 163 |
+
# ComfyUI (還是保留,以免混用)
|
| 164 |
+
elif 'prompt' in info:
|
| 165 |
+
raw_data = info['prompt'] # JSON 格式
|
| 166 |
+
elif 'workflow' in info:
|
| 167 |
+
raw_data = info['workflow']
|
| 168 |
+
except: pass
|
| 169 |
+
|
| 170 |
+
# 3. 執行清理邏輯 (只留 Positive)
|
| 171 |
+
return self._clean_a1111_prompt(raw_data)
|
| 172 |
+
|
| 173 |
+
def _on_folder_drop(self, event):
|
| 174 |
+
path = event.data
|
| 175 |
+
if path.startswith('{') and path.endswith('}'): path = path[1:-1]
|
| 176 |
+
if os.path.isdir(path):
|
| 177 |
+
threading.Thread(target=self._process_directory, args=(path,), daemon=True).start()
|
| 178 |
+
|
| 179 |
+
def _process_directory(self, folder_path):
|
| 180 |
+
self.image_index = []
|
| 181 |
+
self.prompt_counts.clear()
|
| 182 |
+
|
| 183 |
+
valid_exts = ('.png', '.jpg', '.jpeg', '.webp')
|
| 184 |
+
try:
|
| 185 |
+
files = [f for f in os.listdir(folder_path) if f.lower().endswith(valid_exts)]
|
| 186 |
+
except: return
|
| 187 |
+
|
| 188 |
+
total = len(files)
|
| 189 |
+
|
| 190 |
+
for idx, f in enumerate(files):
|
| 191 |
+
img_path = os.path.join(folder_path, f)
|
| 192 |
+
|
| 193 |
+
# 這裡拿到的已經是「乾淨的正向 Prompt」
|
| 194 |
+
clean_prompt = self._extract_metadata(img_path)
|
| 195 |
+
|
| 196 |
+
# --- 統計邏輯 ---
|
| 197 |
+
# 簡單清理一些標點符號,讓統計更準確
|
| 198 |
+
words = clean_prompt.replace('\n', ',').replace('(', '').replace(')', '').split(',')
|
| 199 |
+
|
| 200 |
+
unique_words = set(w.strip().lower() for w in words if w.strip())
|
| 201 |
+
|
| 202 |
+
# 過濾常見無意義詞彙
|
| 203 |
+
stop_words = {'masterpiece', 'best quality', 'highres', 'absurdres', '4k', '8k'}
|
| 204 |
+
filtered_words = [w for w in unique_words if len(w) > 2 and w not in stop_words]
|
| 205 |
+
|
| 206 |
+
self.prompt_counts.update(filtered_words)
|
| 207 |
+
|
| 208 |
+
self.image_index.append({
|
| 209 |
+
"path": img_path,
|
| 210 |
+
"prompt": clean_prompt.lower(),
|
| 211 |
+
"display_prompt": clean_prompt,
|
| 212 |
+
"mtime": os.path.getmtime(img_path)
|
| 213 |
+
})
|
| 214 |
+
|
| 215 |
+
if idx % 10 == 0:
|
| 216 |
+
self.after(0, lambda t=f"索引中... {idx}/{total}": self.title(t))
|
| 217 |
+
|
| 218 |
+
self.after(0, self._ui_update_after_index)
|
| 219 |
+
|
| 220 |
+
def _ui_update_after_index(self):
|
| 221 |
+
self.title(f"AI 圖庫管理器 - {len(self.image_index)} 張")
|
| 222 |
+
self._render_stats_buttons()
|
| 223 |
+
self._filter_and_render_gallery()
|
| 224 |
+
|
| 225 |
+
def _update_stats_limit(self, value):
|
| 226 |
+
self._render_stats_buttons()
|
| 227 |
+
|
| 228 |
+
def _render_stats_buttons(self):
|
| 229 |
+
for w in self.stats_scroll.winfo_children(): w.destroy()
|
| 230 |
+
|
| 231 |
+
try: limit = int(self.top_k_var.get())
|
| 232 |
+
except: limit = 20
|
| 233 |
+
|
| 234 |
+
for word, count in self.prompt_counts.most_common(limit):
|
| 235 |
+
disp = (word[:22] + "...") if len(word) > 25 else word
|
| 236 |
+
btn = ctk.CTkButton(self.stats_scroll, text=f"{disp} ({count})",
|
| 237 |
+
fg_color="transparent", border_width=1, anchor="w", height=24,
|
| 238 |
+
command=lambda w=word: self.search_var.set(w))
|
| 239 |
+
btn.pack(pady=2, fill="x")
|
| 240 |
+
|
| 241 |
+
def _on_search_change(self, *args):
|
| 242 |
+
self._filter_and_render_gallery(self.search_var.get().lower())
|
| 243 |
+
|
| 244 |
+
def _filter_and_render_gallery(self, keyword=""):
|
| 245 |
+
for w in self.gallery_frame.winfo_children(): w.destroy()
|
| 246 |
+
|
| 247 |
+
if not keyword:
|
| 248 |
+
filtered = sorted(self.image_index, key=lambda x: x['mtime'], reverse=True)[:20]
|
| 249 |
+
label_text = "最新生成的 20 張圖片"
|
| 250 |
+
else:
|
| 251 |
+
filtered = sorted([i for i in self.image_index if keyword in i['prompt']],
|
| 252 |
+
key=lambda x: x['mtime'], reverse=True)[:50]
|
| 253 |
+
label_text = f"搜尋 '{keyword}' 結果: {len(filtered)} 筆"
|
| 254 |
+
|
| 255 |
+
self.gallery_frame.configure(label_text=label_text)
|
| 256 |
+
|
| 257 |
+
if not filtered:
|
| 258 |
+
ctk.CTkLabel(self.gallery_frame, text="無圖片").pack(pady=20)
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
columns = 4
|
| 262 |
+
for idx, data in enumerate(filtered):
|
| 263 |
+
try:
|
| 264 |
+
pil_img = Image.open(data['path'])
|
| 265 |
+
pil_img.thumbnail((180, 180))
|
| 266 |
+
ctk_img = ctk.CTkImage(light_image=pil_img, dark_image=pil_img, size=pil_img.size)
|
| 267 |
+
|
| 268 |
+
card = ctk.CTkFrame(self.gallery_frame, fg_color="gray20")
|
| 269 |
+
card.grid(row=idx//columns, column=idx%columns, padx=5, pady=5, sticky="nsew")
|
| 270 |
+
|
| 271 |
+
lbl = ctk.CTkLabel(card, image=ctk_img, text="")
|
| 272 |
+
lbl.pack(padx=5, pady=5)
|
| 273 |
+
|
| 274 |
+
lbl.bind("<Button-1>", lambda e, p=data['path'], txt=data['display_prompt']: self._open_lightbox(p, txt))
|
| 275 |
+
lbl.bind("<Button-3>", lambda e, p=data['path']: self._show_context_menu(e, p))
|
| 276 |
+
|
| 277 |
+
fname = os.path.basename(data['path'])
|
| 278 |
+
ctk.CTkLabel(card, text=fname[:15]+"..." if len(fname)>15 else fname,
|
| 279 |
+
font=("Arial", 10)).pack(pady=(0,5))
|
| 280 |
+
except Exception as e:
|
| 281 |
+
print(e)
|
| 282 |
+
|
| 283 |
+
def _open_lightbox(self, path, prompt_text):
|
| 284 |
+
ImageViewer(self, path, prompt_text)
|
| 285 |
+
|
| 286 |
+
def _show_context_menu(self, event, path):
|
| 287 |
+
self.selected_image_path = path
|
| 288 |
+
try:
|
| 289 |
+
self.context_menu.tk_popup(event.x_root, event.y_root)
|
| 290 |
+
finally:
|
| 291 |
+
self.context_menu.grab_release()
|
| 292 |
+
|
| 293 |
+
def _download_current_image(self):
|
| 294 |
+
if not self.selected_image_path: return
|
| 295 |
+
src_path = self.selected_image_path
|
| 296 |
+
dest_path = filedialog.asksaveasfilename(
|
| 297 |
+
defaultextension=".png", initialfile=os.path.basename(src_path),
|
| 298 |
+
filetypes=[("PNG", "*.png"), ("All", "*.*")])
|
| 299 |
+
if dest_path:
|
| 300 |
+
shutil.copy2(src_path, dest_path)
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
app = AIImageManagerV5()
|
| 304 |
+
app.mainloop()
|