e8857bcd by shady

Complete PySide6 migration: Replace tkinter with Qt

- Installed PySide6 6.10.1
- Implemented LoginDialog with QDialog (replaces LoginWindow)
- Implemented ImageGeneratorWindow with QMainWindow
- Implemented ImageGenerationWorker with QThread for async operations
- Preserved all functionality: authentication, image generation, config management
- Applied QSS styling for modern UI
- All Phase 1-3 tasks completed (coding)
- Phase 4 tasks (manual testing) ready for user
1 parent 6a204244
#!/usr/bin/env python3
"""
Gemini Image Generator App
Simple GUI application for generating images using Google's Gemini API
Gemini Image Generator App - PySide6 Version
Modern GUI application for generating images using Google's Gemini API
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from PIL import Image, ImageTk
from PySide6.QtWidgets import (
QApplication, QMainWindow, QDialog, QWidget,
QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout,
QLabel, QLineEdit, QPushButton, QCheckBox, QTextEdit,
QComboBox, QScrollArea, QGroupBox, QFileDialog, QMessageBox
)
from PySide6.QtCore import Qt, QThread, Signal, QSize
from PySide6.QtGui import QPixmap, QFont, QIcon, QDesktopServices
from PySide6.QtCore import QUrl
from PIL import Image
import base64
import io
import json
import os
import sys
import tempfile
import subprocess
import platform
from pathlib import Path
from google import genai
from google.genai import types
import threading
import hashlib
import pymysql
from datetime import datetime
......@@ -73,224 +79,194 @@ class DatabaseManager:
return False, f"认证失败: {str(e)}"
class LoginWindow:
"""登录窗口类"""
class LoginDialog(QDialog):
"""Qt-based login dialog"""
def __init__(self, db_config, last_user="", saved_password_hash=""):
super().__init__()
self.db_config = db_config
self.last_user = last_user
self.saved_password_hash = saved_password_hash
self.success = False
self.authenticated_user = ""
self.password_changed = False # 标记密码是否被修改
self.password_changed = False
self.current_password_hash = ""
# 创建登录窗口
self.root = tk.Tk()
self.root.title("登录 - AI 图像生成器")
self.root.geometry("400x400")
self.root.resizable(False, False)
# 创建 BooleanVar (必须在 Tk 根窗口创建之后)
self.remember_user = tk.BooleanVar(value=bool(last_user))
self.remember_password = tk.BooleanVar(value=bool(saved_password_hash))
self.setup_ui()
self.apply_styles()
# 设置窗口居中
self.center_window()
def setup_ui(self):
"""Build login dialog UI"""
self.setWindowTitle("登录 - AI 图像生成器")
self.setFixedSize(400, 400)
# Main layout
main_layout = QVBoxLayout()
main_layout.setContentsMargins(40, 40, 40, 40)
main_layout.setSpacing(20)
# Title
title_label = QLabel("登录")
title_label.setObjectName("title")
title_label.setAlignment(Qt.AlignCenter)
main_layout.addWidget(title_label)
main_layout.addSpacing(10)
# Form layout for username and password
form_layout = QFormLayout()
form_layout.setSpacing(15)
# Username
username_label = QLabel("用户名")
username_label.setObjectName("field_label")
self.username_entry = QLineEdit()
self.username_entry.setText(self.last_user)
form_layout.addRow(username_label, self.username_entry)
# Password
password_label = QLabel("密码")
password_label.setObjectName("field_label")
self.password_entry = QLineEdit()
self.password_entry.setEchoMode(QLineEdit.Password)
# Handle saved password placeholder
if self.saved_password_hash:
self.password_entry.setPlaceholderText("••••••••")
self.password_entry.setStyleSheet("QLineEdit { color: #999999; }")
# 设置样式
self.setup_styles()
self.password_entry.textChanged.connect(self.on_password_change)
self.password_entry.returnPressed.connect(self.on_login)
# 创建UI
self.setup_ui()
form_layout.addRow(password_label, self.password_entry)
# 绑定回车键
self.root.bind('<Return>', lambda e: self.on_login())
main_layout.addLayout(form_layout)
# 处理窗口关闭
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# Checkboxes
checkbox_layout = QHBoxLayout()
self.remember_user_check = QCheckBox("记住用户名")
self.remember_user_check.setChecked(bool(self.last_user))
checkbox_layout.addWidget(self.remember_user_check)
def center_window(self):
"""窗口居中显示"""
self.root.update_idletasks()
width = self.root.winfo_width()
height = self.root.winfo_height()
x = (self.root.winfo_screenwidth() // 2) - (width // 2)
y = (self.root.winfo_screenheight() // 2) - (height // 2)
self.root.geometry(f'{width}x{height}+{x}+{y}')
self.remember_password_check = QCheckBox("记住密码")
self.remember_password_check.setChecked(bool(self.saved_password_hash))
checkbox_layout.addWidget(self.remember_password_check)
def setup_styles(self):
"""设置样式"""
style = ttk.Style()
style.theme_use('clam')
checkbox_layout.addStretch()
main_layout.addLayout(checkbox_layout)
bg_color = '#ffffff'
accent_color = '#007AFF'
# Login button
self.login_button = QPushButton("登录")
self.login_button.setObjectName("login_button")
self.login_button.clicked.connect(self.on_login)
main_layout.addWidget(self.login_button)
self.root.configure(bg=bg_color)
# Error label
self.error_label = QLabel("")
self.error_label.setObjectName("error_label")
self.error_label.setAlignment(Qt.AlignCenter)
self.error_label.setWordWrap(True)
main_layout.addWidget(self.error_label)
style.configure('TFrame', background=bg_color)
style.configure('TLabel', background=bg_color)
main_layout.addStretch()
style.configure('Login.TButton',
background=accent_color,
foreground='white',
borderwidth=0,
focuscolor='none',
font=('Segoe UI', 10, 'bold'),
padding=(20, 10))
self.setLayout(main_layout)
style.map('Login.TButton',
background=[('active', '#0051D5'), ('pressed', '#0051D5')])
def setup_ui(self):
"""创建登录界面"""
# 主容器
main_frame = tk.Frame(self.root, bg='white', padx=40, pady=40)
main_frame.pack(fill="both", expand=True)
# 标题
title_label = tk.Label(main_frame, text="登录",
font=('Segoe UI', 20, 'bold'),
bg='white', fg='#1d1d1f')
title_label.pack(pady=(0, 30))
# 用户名
username_frame = tk.Frame(main_frame, bg='white')
username_frame.pack(fill="x", pady=(0, 15))
username_label = tk.Label(username_frame, text="用户名",
font=('Segoe UI', 10),
bg='white', fg='#666666')
username_label.pack(anchor="w")
self.username_entry = tk.Entry(username_frame,
font=('Segoe UI', 11),
relief='solid',
borderwidth=1,
bg='#fafafa',
fg='#000000',
insertbackground='#000000')
self.username_entry.pack(fill="x", ipady=8, pady=(5, 0))
self.username_entry.insert(0, self.last_user)
# 密码
password_frame = tk.Frame(main_frame, bg='white')
password_frame.pack(fill="x", pady=(0, 15))
password_label = tk.Label(password_frame, text="密码",
font=('Segoe UI', 10),
bg='white', fg='#666666')
password_label.pack(anchor="w")
self.password_entry = tk.Entry(password_frame,
font=('Segoe UI', 11),
relief='solid',
borderwidth=1,
show='*',
bg='#fafafa',
fg='#000000',
insertbackground='#000000')
self.password_entry.pack(fill="x", ipady=8, pady=(5, 0))
# 如果有保存的密码,显示占位符
if self.saved_password_hash:
self.password_entry.insert(0, "••••••••")
self.password_entry.config(fg='#999999')
# 监听密码框变化
self.password_entry.bind('<KeyPress>', self.on_password_change)
self.password_entry.bind('<Return>', lambda e: self.on_login())
# 复选框容器
checkbox_frame = tk.Frame(main_frame, bg='white')
checkbox_frame.pack(fill="x", pady=(0, 20))
# 记住用户名复选框
remember_user_check = tk.Checkbutton(checkbox_frame,
text="记住用户名",
variable=self.remember_user,
font=('Segoe UI', 9),
bg='white',
activebackground='white')
remember_user_check.pack(side="left")
# 记住密码复选框
remember_password_check = tk.Checkbutton(checkbox_frame,
text="记住密码",
variable=self.remember_password,
font=('Segoe UI', 9),
bg='white',
activebackground='white')
remember_password_check.pack(side="left", padx=(20, 0))
# 登录按钮
self.login_button = ttk.Button(main_frame,
text="登录",
style='Login.TButton',
command=self.on_login)
self.login_button.pack(fill="x")
# 错误提示标签
self.error_label = tk.Label(main_frame,
text="",
font=('Segoe UI', 9),
bg='white',
fg='#ff3b30')
self.error_label.pack(pady=(15, 0))
# 焦点设置
# Set focus
if self.last_user:
self.password_entry.focus()
self.password_entry.setFocus()
else:
self.username_entry.focus()
self.username_entry.setFocus()
def apply_styles(self):
"""Apply QSS stylesheet"""
self.setStyleSheet("""
QDialog {
background-color: #ffffff;
}
QLabel#title {
font-size: 20pt;
font-weight: bold;
color: #1d1d1f;
}
QLabel#field_label {
font-size: 10pt;
color: #666666;
}
QLineEdit {
padding: 8px;
border: 1px solid #e5e5e5;
border-radius: 4px;
background-color: #fafafa;
font-size: 11pt;
color: #000000;
}
QLineEdit:focus {
border: 1px solid #007AFF;
}
QPushButton#login_button {
background-color: #007AFF;
color: white;
font-size: 10pt;
font-weight: bold;
padding: 10px 20px;
border: none;
border-radius: 6px;
}
QPushButton#login_button:hover {
background-color: #0051D5;
}
QPushButton#login_button:pressed {
background-color: #003D99;
}
QPushButton#login_button:disabled {
background-color: #cccccc;
}
QCheckBox {
font-size: 9pt;
color: #1d1d1f;
}
QLabel#error_label {
color: #ff3b30;
font-size: 9pt;
}
""")
def on_password_change(self, event):
"""监听密码框变化"""
def on_password_change(self):
"""Handle password field changes"""
if not self.password_changed and self.saved_password_hash:
# 首次修改密码,清空占位符
self.password_entry.delete(0, tk.END)
self.password_entry.config(fg='#000000')
# First change - clear placeholder style
self.password_entry.setStyleSheet("")
self.password_changed = True
def on_login(self):
"""处理登录"""
print("[DEBUG] 登录按钮被点击")
username = self.username_entry.get().strip()
password_input = self.password_entry.get()
print(f"[DEBUG] 用户名: {username}")
print(f"[DEBUG] 密码输入长度: {len(password_input)}")
print(f"[DEBUG] 密码已修改: {self.password_changed}")
print(f"[DEBUG] 有保存的哈希: {bool(self.saved_password_hash)}")
"""Handle login button click"""
username = self.username_entry.text().strip()
password_input = self.password_entry.text()
# 验证输入
# Validate input
if not username:
print("[DEBUG] 用户名为空")
self.show_error("请输入用户名")
return
if not password_input:
print("[DEBUG] 密码为空")
self.show_error("请输入密码")
return
# 禁用按钮,防止重复点击
self.login_button.config(state='disabled')
self.error_label.config(text="正在验证...", fg='#666666')
self.root.update()
# Disable button during authentication
self.login_button.setEnabled(False)
self.error_label.setText("正在验证...")
self.error_label.setStyleSheet("QLabel { color: #666666; }")
# 判断使用保存的密码还是新输入的密码
# Determine which password to use
if not self.password_changed and self.saved_password_hash:
# 使用保存的密码哈希
print("[DEBUG] 使用保存的密码哈希")
password_hash = self.saved_password_hash
else:
# 计算新密码的哈希
print("[DEBUG] 计算新密码的哈希")
password_hash = hash_password(password_input)
# 直接使用哈希值进行数据库验证
# Authenticate
try:
print(f"[DEBUG] 开始连接数据库: {self.db_config['host']}")
conn = pymysql.connect(
host=self.db_config['host'],
port=self.db_config.get('port', 3306),
......@@ -299,175 +275,82 @@ class LoginWindow:
database=self.db_config['database'],
connect_timeout=5
)
print("[DEBUG] 数据库连接成功")
try:
with conn.cursor() as cursor:
sql = f"SELECT * FROM {self.db_config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
print(f"[DEBUG] 执行查询,用户名: {username}, 哈希前8位: {password_hash[:8]}...")
cursor.execute(sql, (username, password_hash))
result = cursor.fetchone()
print(f"[DEBUG] 查询结果: {'找到用户' if result else '未找到匹配'}")
if result:
print("[DEBUG] 登录成功")
self.success = True
self.authenticated_user = username
# 保存密码哈希用于下次登录
self.current_password_hash = password_hash
self.root.quit()
self.root.destroy()
self.accept() # Close dialog with success
else:
print("[DEBUG] 用户名或密码错误")
self.show_error("用户名或密码错误")
self.password_entry.delete(0, tk.END)
self.password_entry.clear()
self.password_changed = False
self.login_button.config(state='normal')
self.login_button.setEnabled(True)
finally:
conn.close()
print("[DEBUG] 数据库连接已关闭")
except pymysql.OperationalError as e:
print(f"[DEBUG] 数据库连接失败: {e}")
except pymysql.OperationalError:
self.show_error("无法连接到服务器,请检查网络连接")
self.login_button.config(state='normal')
self.login_button.setEnabled(True)
except Exception as e:
print(f"[DEBUG] 认证异常: {e}")
self.show_error(f"认证失败: {str(e)}")
self.login_button.config(state='normal')
self.login_button.setEnabled(True)
def show_error(self, message):
"""显示错误信息"""
self.error_label.config(text=message, fg='#ff3b30')
"""Display error message"""
self.error_label.setText(message)
self.error_label.setStyleSheet("QLabel { color: #ff3b30; }")
def on_close(self):
"""处理窗口关闭"""
self.success = False
self.root.quit()
self.root.destroy()
def get_remember_user(self):
"""Get remember username checkbox state"""
return self.remember_user_check.isChecked()
def run(self):
"""运行登录窗口"""
self.root.mainloop()
return (self.success,
self.authenticated_user,
self.remember_user.get(),
self.remember_password.get(),
getattr(self, 'current_password_hash', ''))
def get_remember_password(self):
"""Get remember password checkbox state"""
return self.remember_password_check.isChecked()
def get_password_hash(self):
"""Get current password hash"""
return getattr(self, 'current_password_hash', '')
class ImageGeneratorApp:
def __init__(self, root):
self.root = root
self.root.title("AI 图像生成器")
self.root.geometry("1200x850")
self.root.minsize(1000, 700)
# Configure modern styling
self.setup_styles()
class ImageGeneratorWindow(QMainWindow):
"""Qt-based main application window"""
def __init__(self):
super().__init__()
self.api_key = ""
self.uploaded_images = [] # List of (file_path, PhotoImage) tuples
self.uploaded_images = [] # List of file paths
self.generated_image_data = None
self.generated_image_bytes = None
self.saved_prompts = [] # Store favorite prompts
self.saved_prompts = []
self.db_config = None
self.last_user = ""
self.saved_password_hash = ""
self.load_config()
self.setup_ui()
def setup_styles(self):
"""Setup modern macOS-inspired UI styles"""
style = ttk.Style()
style.theme_use('clam')
# macOS-inspired color palette
bg_color = '#ffffff'
secondary_bg = '#f6f6f6'
accent_color = '#007AFF'
hover_color = '#0051D5'
border_color = '#e5e5e5'
text_color = '#1d1d1f'
self.root.configure(bg=bg_color)
# Primary button style
style.configure('Accent.TButton',
background=accent_color,
foreground='white',
borderwidth=1,
relief='solid',
focuscolor='none',
font=('Segoe UI', 10),
padding=(18, 8))
style.map('Accent.TButton',
background=[('active', hover_color), ('pressed', '#003D99')],
foreground=[('disabled', '#999999')])
# Secondary button style
style.configure('Secondary.TButton',
background=secondary_bg,
foreground=text_color,
borderwidth=1,
relief='solid',
font=('Segoe UI', 9),
padding=(12, 6))
style.map('Secondary.TButton',
background=[('active', '#e8e8e8'), ('pressed', '#c8c8c8')])
# Icon button style (small, subtle)
style.configure('Icon.TButton',
background=bg_color,
foreground='#666666',
borderwidth=1,
relief='solid',
font=('Segoe UI', 9),
padding=(4, 4))
style.map('Icon.TButton',
background=[('active', secondary_bg), ('pressed', '#d8d8d8')],
foreground=[('active', accent_color)])
# Delete button style (visible with red hover)
style.configure('Delete.TButton',
background='#ff4444',
foreground='#ffffff',
borderwidth=1,
relief='solid',
font=('Segoe UI', 9, 'bold'),
padding=(3, 1))
style.map('Delete.TButton',
background=[('active', '#FF3B30'), ('pressed', '#cc0000')],
foreground=[('active', 'white'), ('pressed', 'white')],
borderwidth=[('active', 1)],
relief=[('active', 'solid')])
style.configure('TLabelframe', background=bg_color, borderwidth=0, relief='flat')
style.configure('TLabelframe.Label', background=bg_color, font=('Segoe UI', 10, 'bold'), foreground=text_color)
style.configure('TLabel', background=bg_color, font=('Segoe UI', 9), foreground=text_color)
style.configure('TFrame', background=bg_color)
style.configure('Card.TFrame', background=secondary_bg, relief='flat')
style.configure('TCombobox', font=('Segoe UI', 9))
self.apply_styles()
def get_config_dir(self):
"""Get the appropriate directory for config files based on platform and mode"""
# Check if running as a bundled app (PyInstaller)
if getattr(sys, 'frozen', False):
# Running as bundled app - use user data directory
system = platform.system()
if system == 'Darwin': # macOS
if system == 'Darwin':
config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
elif system == 'Windows':
config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
else: # Linux and others
else:
config_dir = Path.home() / '.config' / 'zb100imagegenerator'
else:
# Running in development mode - use current directory
config_dir = Path('.')
# Create directory if it doesn't exist
config_dir.mkdir(parents=True, exist_ok=True)
return config_dir
......@@ -479,12 +362,6 @@ class ImageGeneratorApp:
"""Load API key, saved prompts, and db config from config file"""
config_path = self.get_config_path()
# 初始化默认值
self.db_config = None
self.last_user = ""
self.saved_password_hash = ""
# Try to load from user config first
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
......@@ -497,10 +374,8 @@ class ImageGeneratorApp:
except Exception as e:
print(f"Failed to load config from {config_path}: {e}")
# If no config found and we're in bundled mode, try to load from bundled resources
if not self.api_key and getattr(sys, 'frozen', False):
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
bundle_dir = Path(sys._MEIPASS)
bundled_config = bundle_dir / 'config.json'
if bundled_config.exists():
......@@ -508,14 +383,12 @@ class ImageGeneratorApp:
config = json.load(f)
self.api_key = config.get("api_key", "")
self.db_config = config.get("db_config")
# Don't load saved_prompts from bundle, only API key
# Save to user config for future use
self.save_config()
except Exception as e:
print(f"Failed to load bundled config: {e}")
if not self.api_key:
messagebox.showwarning("警告", f"未找到API密钥\n配置文件位置: {config_path}\n\n请在应用中输入API密钥或手动编辑配置文件")
QMessageBox.warning(self, "警告", f"未找到API密钥\n配置文件位置: {config_path}\n\n请在应用中输入API密钥或手动编辑配置文件")
def save_config(self, last_user=None):
"""Save configuration to file"""
......@@ -527,11 +400,9 @@ class ImageGeneratorApp:
"saved_prompts": self.saved_prompts
}
# 添加数据库配置(如果存在)
if self.db_config:
config["db_config"] = self.db_config
# 添加最后登录用户
if last_user is not None:
config["last_user"] = last_user
elif hasattr(self, 'last_user'):
......@@ -539,423 +410,535 @@ class ImageGeneratorApp:
else:
config["last_user"] = ""
# 添加保存的密码哈希
if hasattr(self, 'saved_password_hash'):
config["saved_password_hash"] = self.saved_password_hash
else:
config["saved_password_hash"] = ""
# Ensure directory exists
config_path.parent.mkdir(parents=True, exist_ok=True)
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
except Exception as e:
messagebox.showerror("错误", f"保存配置失败: {str(e)}\n路径: {config_path}")
QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}\n路径: {config_path}")
def setup_ui(self):
"""Setup the user interface with macOS-inspired design"""
# Main container
main_container = ttk.Frame(self.root, padding=20)
main_container.pack(fill="both", expand=True)
# Reference Images Section with preview
ref_frame = ttk.LabelFrame(main_container, text="参考图片", padding=12)
ref_frame.pack(fill="x", pady=(0, 15))
# Upload button and info
upload_header = ttk.Frame(ref_frame)
upload_header.pack(fill="x", pady=(0, 8))
upload_btn = ttk.Button(upload_header, text="+ 添加图片",
command=self.upload_images,
style='Secondary.TButton')
upload_btn.pack(side="left")
self.bind_hover_effect(upload_btn)
self.image_count_label = ttk.Label(upload_header, text="已选择 0 张", foreground='#666666')
self.image_count_label.pack(side="left", padx=12)
# Image preview container (horizontal scrollable)
preview_container = ttk.Frame(ref_frame, style='Card.TFrame', height=140)
preview_container.pack(fill="x", pady=(0, 0))
preview_container.pack_propagate(False)
# Canvas for horizontal scrolling (without visible scrollbar)
self.img_canvas = tk.Canvas(preview_container, height=110, bg='#f6f6f6',
highlightthickness=0, bd=0)
self.img_preview_frame = ttk.Frame(self.img_canvas, style='Card.TFrame')
self.img_preview_frame.bind("<Configure>",
lambda e: self.img_canvas.configure(scrollregion=self.img_canvas.bbox("all")))
self.img_canvas.create_window((0, 0), window=self.img_preview_frame, anchor="nw")
# Enable mouse wheel scrolling
self.img_canvas.bind('<MouseWheel>', self._on_mousewheel)
self.img_canvas.bind('<Shift-MouseWheel>', self._on_mousewheel)
self.img_canvas.pack(fill="both", expand=True)
# Content area: Prompt (left) + Settings (right)
content_row = ttk.Frame(main_container)
content_row.pack(fill="x", pady=(0, 15))
# Left: Prompt Section
prompt_container = ttk.LabelFrame(content_row, text="提示词", padding=12)
prompt_container.pack(side="left", fill="both", expand=True, padx=(0, 10))
"""Setup the user interface"""
self.setWindowTitle("AI 图像生成器")
self.setGeometry(100, 100, 1200, 850)
self.setMinimumSize(1000, 700)
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout()
main_layout.setContentsMargins(20, 20, 20, 20)
main_layout.setSpacing(15)
# Reference images section
ref_group = QGroupBox("参考图片")
ref_layout = QVBoxLayout()
# Upload button and count
upload_header = QHBoxLayout()
upload_btn = QPushButton("+ 添加图片")
upload_btn.clicked.connect(self.upload_images)
upload_header.addWidget(upload_btn)
self.image_count_label = QLabel("已选择 0 张")
upload_header.addWidget(self.image_count_label)
upload_header.addStretch()
ref_layout.addLayout(upload_header)
# Image preview scroll area
self.img_scroll = QScrollArea()
self.img_scroll.setWidgetResizable(True)
self.img_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.img_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.img_scroll.setFixedHeight(140)
self.img_container = QWidget()
self.img_layout = QHBoxLayout()
self.img_layout.addStretch()
self.img_container.setLayout(self.img_layout)
self.img_scroll.setWidget(self.img_container)
ref_layout.addWidget(self.img_scroll)
ref_group.setLayout(ref_layout)
main_layout.addWidget(ref_group)
# Content row: Prompt (left) + Settings (right)
content_row = QHBoxLayout()
# Prompt section
prompt_group = QGroupBox("提示词")
prompt_layout = QVBoxLayout()
# Prompt toolbar
prompt_toolbar = ttk.Frame(prompt_container)
prompt_toolbar.pack(fill="x", pady=(0, 8))
self.save_prompt_btn = ttk.Button(prompt_toolbar, text="⭐ 收藏",
command=self.toggle_favorite,
style='Icon.TButton')
self.save_prompt_btn.pack(side="left", padx=(0, 5))
self.bind_hover_effect(self.save_prompt_btn)
# Saved prompts dropdown
ttk.Label(prompt_toolbar, text="快速选择:", foreground='#666666').pack(side="left", padx=(10, 5))
self.saved_prompts_combo = ttk.Combobox(prompt_toolbar, width=30, state="readonly")
self.saved_prompts_combo.pack(side="left")
self.saved_prompts_combo.bind('<<ComboboxSelected>>', self.load_saved_prompt)
prompt_toolbar = QHBoxLayout()
self.save_prompt_btn = QPushButton("⭐ 收藏")
self.save_prompt_btn.clicked.connect(self.toggle_favorite)
prompt_toolbar.addWidget(self.save_prompt_btn)
prompt_toolbar.addWidget(QLabel("快速选择:"))
self.saved_prompts_combo = QComboBox()
self.saved_prompts_combo.currentIndexChanged.connect(self.load_saved_prompt)
self.update_saved_prompts_list()
# Delete saved prompt button
delete_prompt_btn = ttk.Button(prompt_toolbar, text="🗑️ 删除",
command=self.delete_saved_prompt,
style='Icon.TButton')
delete_prompt_btn.pack(side="left", padx=(5, 0))
self.bind_hover_effect(delete_prompt_btn)
prompt_toolbar.addWidget(self.saved_prompts_combo)
delete_prompt_btn = QPushButton("🗑️ 删除")
delete_prompt_btn.clicked.connect(self.delete_saved_prompt)
prompt_toolbar.addWidget(delete_prompt_btn)
prompt_toolbar.addStretch()
prompt_layout.addLayout(prompt_toolbar)
# Prompt text area
self.prompt_text = scrolledtext.ScrolledText(prompt_container, height=8, wrap=tk.WORD,
font=('Segoe UI', 10),
borderwidth=1, relief='solid',
bg='#fafafa')
self.prompt_text.pack(fill="both", expand=True)
self.prompt_text.insert("1.0", "一幅美丽的风景画,有山有湖,日落时分")
# Bind text change event to check favorite status
self.prompt_text.bind('<<Modified>>', self.on_prompt_change)
# Right: Settings Section
settings_container = ttk.LabelFrame(content_row, text="生成设置", padding=12)
settings_container.pack(side="right", fill="y")
# Aspect Ratio
ttk.Label(settings_container, text="宽高比", foreground='#666666').pack(anchor="w", pady=(0, 4))
self.aspect_ratio = ttk.Combobox(settings_container, width=18, state="readonly")
self.aspect_ratio['values'] = ("1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9")
self.aspect_ratio.current(0)
self.aspect_ratio.pack(fill="x", pady=(0, 12))
# Image Size
ttk.Label(settings_container, text="图片尺寸", foreground='#666666').pack(anchor="w", pady=(0, 4))
self.image_size = ttk.Combobox(settings_container, width=18, state="readonly")
self.image_size['values'] = ("1K", "2K", "4K")
self.image_size.current(1)
self.image_size.pack(fill="x", pady=(0, 0))
self.prompt_text = QTextEdit()
self.prompt_text.setPlainText("一幅美丽的风景画,有山有湖,日落时分")
self.prompt_text.textChanged.connect(self.check_favorite_status)
prompt_layout.addWidget(self.prompt_text)
prompt_group.setLayout(prompt_layout)
content_row.addWidget(prompt_group, 2)
# Settings section
settings_group = QGroupBox("生成设置")
settings_layout = QVBoxLayout()
settings_layout.addWidget(QLabel("宽高比"))
self.aspect_ratio = QComboBox()
self.aspect_ratio.addItems(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"])
settings_layout.addWidget(self.aspect_ratio)
settings_layout.addSpacing(10)
settings_layout.addWidget(QLabel("图片尺寸"))
self.image_size = QComboBox()
self.image_size.addItems(["1K", "2K", "4K"])
self.image_size.setCurrentIndex(1)
settings_layout.addWidget(self.image_size)
settings_layout.addStretch()
settings_group.setLayout(settings_layout)
content_row.addWidget(settings_group, 1)
main_layout.addLayout(content_row)
# Action buttons
action_frame = ttk.Frame(main_container)
action_frame.pack(fill="x", pady=(0, 15))
self.generate_btn = ttk.Button(action_frame, text="生成图片",
command=self.generate_image_async,
style='Accent.TButton')
self.generate_btn.pack(side="left", padx=(0, 10))
self.bind_hover_effect(self.generate_btn, scale=True)
self.download_btn = ttk.Button(action_frame, text="下载图片",
command=self.download_image,
state="disabled",
style='Secondary.TButton')
self.download_btn.pack(side="left", padx=(0, 10))
self.bind_hover_effect(self.download_btn)
self.status_label = ttk.Label(action_frame, text="● 就绪",
font=('Segoe UI', 9),
foreground='#007AFF')
self.status_label.pack(side="left", padx=15)
# Preview Section (expands to fill remaining space)
preview_frame = ttk.LabelFrame(main_container, text="预览", padding=12)
preview_frame.pack(fill="both", expand=True)
# Create a frame to center the image
preview_inner = ttk.Frame(preview_frame)
preview_inner.pack(fill="both", expand=True)
self.preview_label = ttk.Label(preview_inner, text="生成的图片将在这里显示\n双击用系统查看器打开",
anchor="center",
font=('Segoe UI', 10),
foreground='#999999')
self.preview_label.place(relx=0.5, rely=0.5, anchor="center")
# Bind double-click to open with system viewer
self.preview_label.bind('<Double-Button-1>', self.open_fullsize_view)
def _on_mousewheel(self, event):
"""Handle horizontal scrolling with mouse wheel"""
# Shift+Wheel or just Wheel for horizontal scroll
self.img_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
def bind_hover_effect(self, widget, scale=False):
"""Add smooth macOS-style hover effect"""
original_cursor = widget['cursor']
def on_enter(e):
widget['cursor'] = 'hand2'
# Subtle scale effect for primary buttons
if scale and hasattr(widget, 'configure'):
try:
widget.configure(padding=(19, 9))
except:
pass
def on_leave(e):
widget['cursor'] = original_cursor
if scale and hasattr(widget, 'configure'):
action_layout = QHBoxLayout()
self.generate_btn = QPushButton("生成图片")
self.generate_btn.clicked.connect(self.generate_image_async)
action_layout.addWidget(self.generate_btn)
self.download_btn = QPushButton("下载图片")
self.download_btn.clicked.connect(self.download_image)
self.download_btn.setEnabled(False)
action_layout.addWidget(self.download_btn)
self.status_label = QLabel("● 就绪")
action_layout.addWidget(self.status_label)
action_layout.addStretch()
main_layout.addLayout(action_layout)
# Preview section
preview_group = QGroupBox("预览")
preview_layout = QVBoxLayout()
self.preview_label = QLabel("生成的图片将在这里显示\n双击用系统查看器打开")
self.preview_label.setAlignment(Qt.AlignCenter)
self.preview_label.setMinimumHeight(300)
self.preview_label.setStyleSheet("QLabel { color: #999999; font-size: 10pt; }")
self.preview_label.mouseDoubleClickEvent = self.open_fullsize_view
preview_layout.addWidget(self.preview_label)
preview_group.setLayout(preview_layout)
main_layout.addWidget(preview_group, 1)
central_widget.setLayout(main_layout)
self.check_favorite_status()
def apply_styles(self):
"""Apply QSS stylesheet"""
self.setStyleSheet("""
QMainWindow {
background-color: #ffffff;
}
QGroupBox {
font-weight: bold;
font-size: 10pt;
border: 1px solid #e5e5e5;
border-radius: 6px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #1d1d1f;
subcontrol-origin: margin;
left: 10px;
padding: 0 5px;
}
QPushButton {
background-color: #f6f6f6;
color: #1d1d1f;
border: 1px solid #e5e5e5;
border-radius: 4px;
padding: 6px 12px;
font-size: 9pt;
}
QPushButton:hover {
background-color: #e8e8e8;
}
QPushButton:pressed {
background-color: #c8c8c8;
}
QPushButton:disabled {
background-color: #f6f6f6;
color: #999999;
}
QComboBox {
border: 1px solid #e5e5e5;
border-radius: 4px;
padding: 5px;
background-color: white;
}
QTextEdit {
border: 1px solid #e5e5e5;
border-radius: 4px;
background-color: #fafafa;
font-size: 10pt;
}
QLabel {
color: #1d1d1f;
}
QScrollArea {
border: none;
background-color: #f6f6f6;
}
""")
def upload_images(self):
"""Upload reference images"""
files, _ = QFileDialog.getOpenFileNames(
self,
"选择参考图片",
"",
"图片文件 (*.png *.jpg *.jpeg *.gif *.bmp);;所有文件 (*.*)"
)
if files:
for file_path in files:
try:
widget.configure(padding=(18, 8))
except:
pass
widget.bind('<Enter>', on_enter)
widget.bind('<Leave>', on_leave)
self.uploaded_images.append(file_path)
except Exception as e:
QMessageBox.critical(self, "错误", f"无法加载图片: {file_path}\n{str(e)}")
self.update_image_preview()
self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
self.status_label.setText(f"● 已添加 {len(files)} 张参考图片")
self.status_label.setStyleSheet("QLabel { color: #34C759; }")
def update_image_preview(self):
"""Update image preview thumbnails"""
# Clear existing previews
while self.img_layout.count() > 1: # Keep the stretch
item = self.img_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
# Add thumbnails
for idx, file_path in enumerate(self.uploaded_images):
try:
# Load and create thumbnail
pixmap = QPixmap(file_path)
pixmap = pixmap.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# Container
container = QWidget()
container_layout = QVBoxLayout()
container_layout.setContentsMargins(5, 5, 5, 5)
# Image label
img_label = QLabel()
img_label.setPixmap(pixmap)
img_label.setFixedSize(100, 100)
img_label.setStyleSheet("QLabel { border: 1px solid #e5e5e5; }")
container_layout.addWidget(img_label)
# Info row
info_layout = QHBoxLayout()
index_label = QLabel(f"图 {idx + 1}")
index_label.setStyleSheet("QLabel { font-size: 8pt; color: #666666; }")
info_layout.addWidget(index_label)
del_btn = QPushButton("✕")
del_btn.setFixedSize(20, 20)
del_btn.setStyleSheet("""
QPushButton {
background-color: #ff4444;
color: white;
font-weight: bold;
border: none;
border-radius: 3px;
padding: 0px;
}
QPushButton:hover {
background-color: #FF3B30;
}
""")
del_btn.clicked.connect(lambda checked, i=idx: self.delete_image(i))
info_layout.addWidget(del_btn)
container_layout.addLayout(info_layout)
container.setLayout(container_layout)
self.img_layout.insertWidget(self.img_layout.count() - 1, container)
except Exception as e:
print(f"Failed to create thumbnail for {file_path}: {e}")
def delete_image(self, index):
"""Delete an image by index"""
if 0 <= index < len(self.uploaded_images):
self.uploaded_images.pop(index)
self.update_image_preview()
self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
self.status_label.setText("● 已删除图片")
self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
def update_saved_prompts_list(self):
"""Update the saved prompts dropdown"""
self.saved_prompts_combo.clear()
if self.saved_prompts:
# Show first 50 chars of each prompt
display_prompts = [p[:50] + "..." if len(p) > 50 else p for p in self.saved_prompts]
self.saved_prompts_combo['values'] = display_prompts
else:
self.saved_prompts_combo['values'] = []
self.saved_prompts_combo.addItems(display_prompts)
def check_favorite_status(self):
"""Check if current prompt is favorited and update button state"""
prompt = self.prompt_text.get("1.0", tk.END).strip()
"""Check if current prompt is favorited"""
prompt = self.prompt_text.toPlainText().strip()
if prompt in self.saved_prompts:
self.save_prompt_btn.config(text="✓ 已收藏")
self.save_prompt_btn.setText("✓ 已收藏")
else:
self.save_prompt_btn.config(text="⭐ 收藏")
def on_prompt_change(self, event=None):
"""Callback when prompt text changes"""
# Clear the modified flag to avoid repeated triggers
self.prompt_text.edit_modified(False)
self.check_favorite_status()
self.save_prompt_btn.setText("⭐ 收藏")
def toggle_favorite(self):
"""Toggle favorite status of current prompt"""
prompt = self.prompt_text.get("1.0", tk.END).strip()
prompt = self.prompt_text.toPlainText().strip()
if not prompt:
self.status_label.config(text="● 提示词不能为空", foreground='#FF3B30')
self.status_label.setText("● 提示词不能为空")
self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")
return
if prompt in self.saved_prompts:
# Remove from favorites
self.saved_prompts.remove(prompt)
self.save_config()
self.update_saved_prompts_list()
self.status_label.config(text="● 该提示词已取消收藏", foreground='#34C759')
self.status_label.setText("● 该提示词已取消收藏")
else:
# Add to favorites
self.saved_prompts.append(prompt)
self.save_config()
self.update_saved_prompts_list()
self.status_label.config(text="● 该提示词已收藏", foreground='#34C759')
self.status_label.setText("● 该提示词已收藏")
# Update button state
self.status_label.setStyleSheet("QLabel { color: #34C759; }")
self.check_favorite_status()
def load_saved_prompt(self, event):
def load_saved_prompt(self):
"""Load a saved prompt"""
index = self.saved_prompts_combo.current()
if index >= 0 and index < len(self.saved_prompts):
self.prompt_text.delete("1.0", tk.END)
self.prompt_text.insert("1.0", self.saved_prompts[index])
self.status_label.config(text="● 已加载提示词", foreground='#007AFF')
self.check_favorite_status()
index = self.saved_prompts_combo.currentIndex()
if 0 <= index < len(self.saved_prompts):
self.prompt_text.setPlainText(self.saved_prompts[index])
self.status_label.setText("● 已加载提示词")
self.status_label.setStyleSheet("QLabel { color: #007AFF; }")
def delete_saved_prompt(self):
"""Delete the currently selected saved prompt"""
index = self.saved_prompts_combo.current()
index = self.saved_prompts_combo.currentIndex()
if index < 0 or index >= len(self.saved_prompts):
self.status_label.config(text="● 请先选择要删除的提示词", foreground='#FF9500')
self.status_label.setText("● 请先选择要删除的提示词")
self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
return
# Delete without confirmation - just do it
self.saved_prompts.pop(index)
self.save_config()
self.update_saved_prompts_list()
self.saved_prompts_combo.set('') # Clear selection
self.status_label.config(text="● 已删除提示词", foreground='#34C759')
self.status_label.setText("● 已删除提示词")
self.status_label.setStyleSheet("QLabel { color: #34C759; }")
def upload_images(self):
"""Upload reference images with preview"""
files = filedialog.askopenfilenames(
title="选择参考图片",
filetypes=[("图片文件", "*.png *.jpg *.jpeg *.gif *.bmp"), ("所有文件", "*.*")]
def generate_image_async(self):
"""Start image generation in a separate thread"""
# Create and start worker thread
self.worker = ImageGenerationWorker(
self.api_key,
self.prompt_text.toPlainText().strip(),
self.uploaded_images,
self.aspect_ratio.currentText(),
self.image_size.currentText()
)
self.worker.finished.connect(self.on_image_generated)
self.worker.error.connect(self.on_generation_error)
self.worker.progress.connect(self.update_status)
self.generate_btn.setEnabled(False)
self.download_btn.setEnabled(False)
self.status_label.setText("● 正在生成图片...")
self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
self.worker.start()
def on_image_generated(self, image_bytes):
"""Handle successful image generation"""
self.generated_image_bytes = image_bytes
self.display_image()
self.download_btn.setEnabled(True)
self.generate_btn.setEnabled(True)
self.status_label.setText("● 图片生成成功")
self.status_label.setStyleSheet("QLabel { color: #34C759; }")
def on_generation_error(self, error_msg):
"""Handle image generation error"""
QMessageBox.critical(self, "错误", f"生成失败: {error_msg}")
self.generate_btn.setEnabled(True)
self.status_label.setText("● 生成失败")
self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")
def update_status(self, message):
"""Update status label"""
self.status_label.setText(f"● {message}")
if files:
for file_path in files:
try:
# Load and create thumbnail with uniform size
img = Image.open(file_path)
# Create 100x100 square thumbnail with center crop
thumb_size = 100
img_copy = img.copy()
# Calculate crop box for center crop
width, height = img_copy.size
aspect = width / height
if aspect > 1: # Landscape
new_width = int(height * 1)
left = (width - new_width) // 2
crop_box = (left, 0, left + new_width, height)
elif aspect < 1: # Portrait
new_height = int(width * 1)
top = (height - new_height) // 2
crop_box = (0, top, width, top + new_height)
else: # Square
crop_box = (0, 0, width, height)
# Crop to square and resize
img_square = img_copy.crop(crop_box)
img_square = img_square.resize((thumb_size, thumb_size), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(img_square)
# Add to list maintaining order
self.uploaded_images.append((file_path, photo))
except Exception as e:
messagebox.showerror("错误", f"无法加载图片: {file_path}\n{str(e)}")
self.update_image_preview()
self.image_count_label.config(text=f"已选择 {len(self.uploaded_images)} 张")
self.status_label.config(text=f"● 已添加 {len(files)} 张参考图片", foreground='#34C759')
def update_image_preview(self):
"""Update the image preview panel"""
# Clear existing previews
for widget in self.img_preview_frame.winfo_children():
widget.destroy()
# Nothing to show if no images
if not self.uploaded_images:
def display_image(self):
"""Display generated image in preview"""
if not self.generated_image_bytes:
return
# Add each image with delete button
for idx, (file_path, photo) in enumerate(self.uploaded_images):
# Container for each image
img_container = ttk.Frame(self.img_preview_frame, style='Card.TFrame')
img_container.pack(side="left", padx=5, pady=5)
# Store reference in container to prevent garbage collection
img_container._photo_ref = photo
# Image label
img_label = ttk.Label(img_container, image=photo, relief='solid', borderwidth=1)
img_label.image = photo # Keep reference
img_label.pack()
# Info frame (index + delete button)
info_frame = ttk.Frame(img_container, style='Card.TFrame')
info_frame.pack(fill="x", pady=(2, 0))
# Image index
index_label = ttk.Label(info_frame, text=f"图 {idx + 1}",
font=('Segoe UI', 8), foreground='#666666')
index_label.pack(side="left", padx=2)
# Delete button with enhanced visibility
del_btn = ttk.Button(info_frame, text="✕", width=3,
command=lambda i=idx: self.delete_image(i),
style='Delete.TButton')
del_btn.pack(side="right")
# Enhanced hover effect for delete button
def on_delete_hover(e, btn=del_btn):
btn['cursor'] = 'hand2'
def on_delete_leave(e, btn=del_btn):
btn['cursor'] = ''
del_btn.bind('<Enter>', on_delete_hover)
del_btn.bind('<Leave>', on_delete_leave)
# Force canvas to update scrollregion
self.img_canvas.update_idletasks()
def delete_image(self, index):
"""Delete a specific image by index"""
if 0 <= index < len(self.uploaded_images):
self.uploaded_images.pop(index)
self.update_image_preview()
self.image_count_label.config(text=f"已选择 {len(self.uploaded_images)} 张")
self.status_label.config(text="● 已删除图片", foreground='#FF9500')
try:
# Load image from bytes
pixmap = QPixmap()
pixmap.loadFromData(self.generated_image_bytes)
# Scale to fit preview area
available_width = self.preview_label.width() - 40
available_height = self.preview_label.height() - 40
scaled_pixmap = pixmap.scaled(
available_width, available_height,
Qt.KeepAspectRatio,
Qt.SmoothTransformation
)
self.preview_label.setPixmap(scaled_pixmap)
self.preview_label.setStyleSheet("")
except Exception as e:
QMessageBox.critical(self, "错误", f"图片显示失败: {str(e)}")
def image_to_base64(self, image_path):
"""Convert image file to base64 string"""
with open(image_path, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def generate_image_async(self):
"""Start image generation in a separate thread"""
thread = threading.Thread(target=self.generate_image, daemon=True)
thread.start()
def open_fullsize_view(self, event):
"""Open generated image with system default viewer"""
if not self.generated_image_bytes:
return
def generate_image(self):
"""Generate image using Gemini API"""
prompt = self.prompt_text.get("1.0", tk.END).strip()
try:
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.png', mode='wb') as tmp_file:
tmp_file.write(self.generated_image_bytes)
tmp_path = tmp_file.name
if not prompt:
self.root.after(0, lambda: messagebox.showerror("错误", "请输入图片描述!"))
return
# Open with system default viewer
url = QUrl.fromLocalFile(tmp_path)
QDesktopServices.openUrl(url)
if not self.api_key:
self.root.after(0, lambda: messagebox.showerror("错误", "未找到API密钥,请在config.json中配置!"))
self.status_label.setText("● 已用系统查看器打开")
self.status_label.setStyleSheet("QLabel { color: #007AFF; }")
except Exception as e:
QMessageBox.critical(self, "错误", f"无法打开系统图片查看器: {str(e)}")
def download_image(self):
"""Download generated image"""
if not self.generated_image_bytes:
QMessageBox.critical(self, "错误", "没有可下载的图片!")
return
self.root.after(0, lambda: self.status_label.config(text="● 正在生成图片...", foreground='#FF9500'))
self.root.after(0, lambda: self.generate_btn.config(state="disabled"))
self.root.after(0, lambda: self.download_btn.config(state="disabled"))
# Generate default filename
default_filename = datetime.now().strftime("%Y%m%d%H%M%S.png")
file_path, _ = QFileDialog.getSaveFileName(
self,
"保存图片",
default_filename,
"PNG 文件 (*.png);;JPEG 文件 (*.jpg);;所有文件 (*.*)"
)
if file_path:
try:
with open(file_path, 'wb') as f:
f.write(self.generated_image_bytes)
file_size = len(self.generated_image_bytes)
QMessageBox.information(self, "成功", f"图片已保存到:\n{file_path}\n\n文件大小: {file_size:,} 字节")
self.status_label.setText("● 图片已保存")
self.status_label.setStyleSheet("QLabel { color: #34C759; }")
except Exception as e:
QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")
class ImageGenerationWorker(QThread):
"""Worker thread for image generation"""
finished = Signal(bytes)
error = Signal(str)
progress = Signal(str)
def __init__(self, api_key, prompt, images, aspect_ratio, image_size):
super().__init__()
self.api_key = api_key
self.prompt = prompt
self.images = images
self.aspect_ratio = aspect_ratio
self.image_size = image_size
def run(self):
"""Execute image generation in background thread"""
try:
if not self.prompt:
self.error.emit("请输入图片描述!")
return
if not self.api_key:
self.error.emit("未找到API密钥,请在config.json中配置!")
return
self.progress.emit("正在连接 Gemini API...")
client = genai.Client(api_key=self.api_key)
# Build content parts
content_parts = [prompt]
content_parts = [self.prompt]
# Add reference images
for img_path in self.images:
with open(img_path, 'rb') as f:
img_data = f.read()
# Add reference images if uploaded
for img_path, _ in self.uploaded_images:
img_data = self.image_to_base64(img_path)
mime_type = "image/png"
if img_path.lower().endswith('.jpg') or img_path.lower().endswith('.jpeg'):
if img_path.lower().endswith(('.jpg', '.jpeg')):
mime_type = "image/jpeg"
content_parts.append(
types.Part.from_bytes(
data=base64.b64decode(img_data),
data=img_data,
mime_type=mime_type
)
)
# Generation config - using snake_case field names
self.progress.emit("正在生成图片...")
# Generation config
config = types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=self.aspect_ratio.get(),
image_size=self.image_size.get()
aspect_ratio=self.aspect_ratio,
image_size=self.image_size
)
)
......@@ -966,125 +949,26 @@ class ImageGeneratorApp:
config=config
)
# Extract image - Fixed for proper data handling
# Extract image
for part in response.parts:
if hasattr(part, 'inline_data') and part.inline_data:
# Store both base64 string and raw bytes
if isinstance(part.inline_data.data, bytes):
self.generated_image_bytes = part.inline_data.data
self.generated_image_data = base64.b64encode(part.inline_data.data).decode('utf-8')
image_bytes = part.inline_data.data
else:
self.generated_image_data = part.inline_data.data
self.generated_image_bytes = base64.b64decode(part.inline_data.data)
image_bytes = base64.b64decode(part.inline_data.data)
self.root.after(0, self.display_image)
self.root.after(0, lambda: self.download_btn.config(state="normal"))
self.root.after(0, lambda: self.status_label.config(text="● 图片生成成功", foreground='#34C759'))
self.finished.emit(image_bytes)
return
raise Exception("响应中没有图片数据")
self.error.emit("响应中没有图片数据")
except Exception as e:
error_msg = str(e)
self.root.after(0, lambda: messagebox.showerror("错误", f"生成失败: {error_msg}"))
self.root.after(0, lambda: self.status_label.config(text="● 生成失败", foreground='#FF3B30'))
finally:
self.root.after(0, lambda: self.generate_btn.config(state="normal"))
def display_image(self):
"""Display generated image in preview with proper scaling"""
if not self.generated_image_bytes:
return
try:
# Use raw bytes directly for display
image = Image.open(io.BytesIO(self.generated_image_bytes))
# Get available space (account for padding and labels)
preview_frame = self.preview_label.master
self.root.update_idletasks()
available_width = preview_frame.winfo_width() - 40
available_height = preview_frame.winfo_height() - 40
# Ensure minimum size
available_width = max(available_width, 400)
available_height = max(available_height, 300)
# Calculate scale to fit while maintaining aspect ratio
img_width, img_height = image.size
scale_w = available_width / img_width
scale_h = available_height / img_height
scale = min(scale_w, scale_h, 1.0) # Don't upscale
new_width = int(img_width * scale)
new_height = int(img_height * scale)
# Resize image
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(image)
self.preview_label.config(image=photo, text="", cursor="hand2")
self.preview_label.image = photo
except Exception as e:
error_msg = str(e)
messagebox.showerror("错误", f"图片显示失败: {error_msg}")
def open_fullsize_view(self, event=None):
"""Open generated image with system default viewer"""
if not self.generated_image_bytes:
return
try:
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.png', mode='wb') as tmp_file:
tmp_file.write(self.generated_image_bytes)
tmp_path = tmp_file.name
# Open with system default viewer
system = platform.system()
if system == 'Windows':
os.startfile(tmp_path)
elif system == 'Darwin': # macOS
subprocess.run(['open', tmp_path], check=True)
else: # Linux and others
subprocess.run(['xdg-open', tmp_path], check=True)
self.status_label.config(text="● 已用系统查看器打开", foreground='#007AFF')
except Exception as e:
messagebox.showerror("错误", f"无法打开系统图片查看器: {str(e)}")
def download_image(self):
"""Download generated image"""
if not self.generated_image_bytes:
messagebox.showerror("错误", "没有可下载的图片!")
return
# 生成默认文件名: 时间戳格式 YYYYMMDDHHMMSS.png
default_filename = datetime.now().strftime("%Y%m%d%H%M%S.png")
file_path = filedialog.asksaveasfilename(
defaultextension=".png",
initialfile=default_filename,
filetypes=[("PNG 文件", "*.png"), ("JPEG 文件", "*.jpg"), ("所有文件", "*.*")],
title="保存图片"
)
if file_path:
try:
# Use raw bytes directly for saving
with open(file_path, 'wb') as f:
f.write(self.generated_image_bytes)
file_size = len(self.generated_image_bytes)
messagebox.showinfo("成功", f"图片已保存到:\n{file_path}\n\n文件大小: {file_size:,} 字节")
self.status_label.config(text="● 图片已保存", foreground='#34C759')
except Exception as e:
messagebox.showerror("错误", f"保存失败: {str(e)}")
self.error.emit(str(e))
def main():
# 首先加载配置以获取数据库信息
"""Main application entry point"""
# Load config for database info
config_dir = Path('.')
if getattr(sys, 'frozen', False):
system = platform.system()
......@@ -1112,48 +996,55 @@ def main():
except Exception as e:
print(f"Failed to load config: {e}")
# 如果没有数据库配置,显示错误并退出
# Create QApplication
app = QApplication(sys.argv)
# Check database config
if not db_config:
root = tk.Tk()
root.withdraw()
messagebox.showerror("配置错误",
QMessageBox.critical(None, "配置错误",
f"未找到数据库配置\n配置文件: {config_path}\n\n"
"请确保 config.json 包含 db_config 字段")
return
# 显示登录窗口
login_window = LoginWindow(db_config, last_user, saved_password_hash)
success, authenticated_user, remember_user, remember_password, password_hash = login_window.run()
# Show login dialog
login_dialog = LoginDialog(db_config, last_user, saved_password_hash)
# 如果登录失败,退出应用
if not success:
return
if login_dialog.exec() == QDialog.Accepted:
# Login successful
authenticated_user = login_dialog.authenticated_user
remember_user = login_dialog.get_remember_user()
remember_password = login_dialog.get_remember_password()
password_hash = login_dialog.get_password_hash()
# 保存/清除 last_user 和密码哈希
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# Save/clear credentials
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
if remember_user:
config["last_user"] = authenticated_user
else:
config["last_user"] = ""
if remember_user:
config["last_user"] = authenticated_user
else:
config["last_user"] = ""
if remember_password:
config["saved_password_hash"] = password_hash
else:
config["saved_password_hash"] = ""
if remember_password:
config["saved_password_hash"] = password_hash
else:
config["saved_password_hash"] = ""
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Failed to save config: {e}")
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Failed to save config: {e}")
# Show main window
main_window = ImageGeneratorWindow()
main_window.show()
# 登录成功,启动主应用
root = tk.Tk()
app = ImageGeneratorApp(root)
root.mainloop()
sys.exit(app.exec())
else:
# Login cancelled or failed
sys.exit(0)
if __name__ == "__main__":
......
......@@ -2,71 +2,71 @@
## Pre-Migration Tasks
1. **Install PySide6 dependency**
- Add `PySide6>=6.6.0` to requirements (if exists) or install directly
- Run `pip install PySide6`
- **Validation**: `python -c "from PySide6.QtWidgets import QApplication; print('OK')"`
1. **[x] Install PySide6 dependency**
- [x] Add `PySide6>=6.6.0` to requirements (if exists) or install directly
- [x] Run `pip install PySide6`
- **Validation**: `python -c "from PySide6.QtWidgets import QApplication; print('OK')"`
2. **Backup current implementation**
- Create git commit of current tkinter version
- Tag as `before-qt-migration` for easy rollback
- **Validation**: `git log --oneline -1` shows commit
2. **[x] Backup current implementation**
- [x] Create git commit of current tkinter version
- [x] Tag as `before-qt-migration` for easy rollback
- **Validation**: `git log --oneline -1` shows commit
## Phase 1: LoginDialog Migration (Priority: Critical)
3. **Create LoginDialog class structure**
- Import PySide6 modules (QDialog, QVBoxLayout, QFormLayout, etc.)
- Define LoginDialog class inheriting from QDialog
- Move __init__ parameters from LoginWindow
- **Validation**: Class instantiates without errors
4. **Implement LoginDialog UI layout**
- Create QVBoxLayout as main layout
- Add title QLabel
- Create QFormLayout for username/password fields
- Add QLineEdit widgets for username and password
- Set password field to QLineEdit.Password mode
- **Validation**: Dialog shows with all fields visible
5. **Add checkbox row to LoginDialog**
- Create QHBoxLayout for checkboxes
- Add "记住用户名" QCheckBox
- Add "记住密码" QCheckBox
- Set initial checked states from parameters
- **Validation**: Checkboxes appear and can be toggled
6. **Add login button and error label**
- Create QPushButton with text "登录"
- Connect to on_login slot
- Add QLabel for error messages (initially hidden)
- **Validation**: Button appears and is clickable
7. **Apply LoginDialog styling**
- Create QSS stylesheet for dialog
- Style title, labels, input fields, button
- Match colors from original design (#ffffff, #007AFF, #fafafa, etc.)
- **Validation**: Dialog matches design mockup
8. **Implement password placeholder handling**
- Check if saved_password_hash exists
- If yes, set placeholder text "••••••••" with gray color
- Bind textChanged signal to clear placeholder
- **Validation**: Placeholder shows and clears on typing
9. **Implement authentication logic**
- Move database connection code to on_login method
- Use pymysql exactly as in tkinter version
- Handle success: set result variables, accept dialog
- Handle failure: show error in error_label
- **Validation**: Login succeeds with valid credentials, fails with invalid
10. **Implement dialog return values**
- Store success, authenticated_user, password_hash as instance variables
- Provide getter methods or properties
- Return QDialog.Accepted on success, QDialog.Rejected on cancel
- **Validation**: Calling code can access all return values
11. **Test LoginDialog on macOS**
3. **[x] Create LoginDialog class structure**
- [x] Import PySide6 modules (QDialog, QVBoxLayout, QFormLayout, etc.)
- [x] Define LoginDialog class inheriting from QDialog
- [x] Move __init__ parameters from LoginWindow
- **Validation**: Class instantiates without errors
4. **[x] Implement LoginDialog UI layout**
- [x] Create QVBoxLayout as main layout
- [x] Add title QLabel
- [x] Create QFormLayout for username/password fields
- [x] Add QLineEdit widgets for username and password
- [x] Set password field to QLineEdit.Password mode
- **Validation**: Dialog shows with all fields visible
5. **[x] Add checkbox row to LoginDialog**
- [x] Create QHBoxLayout for checkboxes
- [x] Add "记住用户名" QCheckBox
- [x] Add "记住密码" QCheckBox
- [x] Set initial checked states from parameters
- **Validation**: Checkboxes appear and can be toggled
6. **[x] Add login button and error label**
- [x] Create QPushButton with text "登录"
- [x] Connect to on_login slot
- [x] Add QLabel for error messages (initially hidden)
- **Validation**: Button appears and is clickable
7. **[x] Apply LoginDialog styling**
- [x] Create QSS stylesheet for dialog
- [x] Style title, labels, input fields, button
- [x] Match colors from original design (#ffffff, #007AFF, #fafafa, etc.)
- **Validation**: Dialog matches design mockup
8. **[x] Implement password placeholder handling**
- [x] Check if saved_password_hash exists
- [x] If yes, set placeholder text "••••••••" with gray color
- [x] Bind textChanged signal to clear placeholder
- **Validation**: Placeholder shows and clears on typing
9. **[x] Implement authentication logic**
- [x] Move database connection code to on_login method
- [x] Use pymysql exactly as in tkinter version
- [x] Handle success: set result variables, accept dialog
- [x] Handle failure: show error in error_label
- **Validation**: Login succeeds with valid credentials, fails with invalid
10. **[x] Implement dialog return values**
- [x] Store success, authenticated_user, password_hash as instance variables
- [x] Provide getter methods or properties
- [x] Return QDialog.Accepted on success, QDialog.Rejected on cancel
- **Validation**: Calling code can access all return values
11. **[ ] Test LoginDialog on macOS**
- Run application and verify dialog appears
- Verify all UI elements are visible (title, labels, inputs, button, checkboxes)
- Test typing in username field
......