9b6295c7 by 柴进

nanobanana初版

0 parents
<!-- OPENSPEC:START -->
# OpenSpec Instructions
These instructions are for AI assistants working in this project.
Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding
Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Keep this managed block so 'openspec update' can refresh the instructions.
<!-- OPENSPEC:END -->
\ No newline at end of file
<!-- OPENSPEC:START -->
# OpenSpec Instructions
These instructions are for AI assistants working in this project.
Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding
Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Keep this managed block so 'openspec update' can refresh the instructions.
<!-- OPENSPEC:END -->
\ No newline at end of file
# Gemini Image Generator
简洁的跨平台桌面应用,使用 Google Gemini API 生成图片。
## 功能特性
- **用户认证**: 基于 MySQL 的登录系统,确保只有授权用户可访问
- 输入文本 Prompt 生成图片
- 支持上传多张参考图片
- 多种图片比例选择(1:1, 16:9, 4:3 等)
- 多种分辨率选择(1K, 2K, 4K)
- 支持两种模型:gemini-2.5-flash-image 和 gemini-3-pro-image-preview
- 实时预览生成的图片
- 一键下载生成的图片
- 跨平台支持(Windows 和 macOS)
## 系统要求
- Python 3.8 或更高版本
- 有效的 Google AI API 密钥
- MySQL 数据库访问权限(用于用户认证)
## 快速开始
### 开发模式运行
1. 安装依赖:
```bash
pip install -r requirements.txt
```
2. 配置数据库和 API 密钥:
- 编辑 `config.json` 文件,配置以下字段:
```json
{
"api_key": "你的Google AI API密钥",
"db_config": {
"host": "你的MySQL主机地址",
"port": 3306,
"user": "数据库用户名",
"password": "数据库密码",
"database": "数据库名",
"table": "nano_banana_users"
},
"last_user": ""
}
```
3. 创建数据库表:
```sql
CREATE TABLE `nano_banana_users` (
`user_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`passwd` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
4. 添加初始用户:
```bash
python user_util.py add admin your_password
```
5. 运行应用:
```bash
python image_generator.py
```
首次运行会显示登录界面,使用创建的账户登录。
### 打包为可执行文件
#### Windows
双击运行 `build_windows.bat` 或在命令行执行:
```cmd
build_windows.bat
```
生成的可执行文件位于 `dist\GeminiImageGenerator.exe`
#### macOS
在终端执行:
```bash
chmod +x build_mac.sh
./build_mac.sh
```
生成的应用程序位于 `dist/GeminiImageGenerator.app`
## 配置文件位置
应用会根据运行模式自动选择配置文件位置:
**开发模式**(直接运行 Python):
- 配置文件:`./config.json`(当前目录)
**打包后的应用**:
- **macOS**: `~/Library/Application Support/ZB100ImageGenerator/config.json`
- **Windows**: `%APPDATA%\ZB100ImageGenerator\config.json`
- **Linux**: `~/.config/zb100imagegenerator/config.json`
首次运行打包应用时,会自动从打包的模板复制 API 密钥到用户目录。
## 用户管理
应用内置用户管理工具 `user_util.py`(仅管理员使用,不随客户端分发)。
### 用户管理命令
```bash
# 添加新用户
python user_util.py add <username> <password>
# 列出所有用户
python user_util.py list
# 禁用用户
python user_util.py disable <username>
# 启用用户
python user_util.py enable <username>
# 重置密码
python user_util.py reset <username> <new_password>
```
### 示例
```bash
# 添加管理员账户
python user_util.py add admin MySecurePass123
# 查看所有用户
python user_util.py list
# 禁用某个用户
python user_util.py disable testuser
# 重置用户密码
python user_util.py reset admin NewPassword456
```
### 安全说明
- 密码使用 SHA256 哈希存储,数据库和本地均不保存明文
- 所有数据库操作使用参数化查询,防止 SQL 注入
- user_util.py 工具仅供管理员使用,不应分发给普通用户
- 应用会记住上次登录的用户名(可选),但不会保存密码
## 使用说明
1. **登录应用**
- 应用启动时显示登录界面
- 输入用户名和密码
- 可勾选"记住用户名"选项,下次自动填充用户名
- 登录成功后进入主界面
2. **配置 API 密钥**
- 编辑配置文件中的 `api_key` 字段
- 或通过应用界面的收藏提示词功能自动保存
3. **上传参考图片(可选)**
- 点击 "添加图片" 按钮选择一张或多张参考图片
- 这些图片将作为生成图片的参考
- 可以单独删除每张图片
3. **输入 Prompt**
- 在提示词文本框中输入你想生成的图片描述
- 可以使用 "收藏" 功能保存常用提示词
- 从下拉菜单快速选择已保存的提示词
4. **选择生成参数**
- **宽高比**: 选择图片的宽高比(1:1, 16:9 等)
- **图片尺寸**: 选择图片的分辨率(1K/2K/4K)
- **AI 模型**: 选择使用的模型
5. **生成图片**
- 点击 "生成图片" 按钮
- 等待生成完成,生成的图片会显示在预览区域
- 双击预览图可用系统默认查看器打开
6. **下载图片**
- 点击 "下载图片" 按钮
- 选择保存位置和文件格式(PNG/JPEG)
## 项目结构
```
Nano_Banana_App/
├── image_generator.py # 主程序文件(含登录界面和数据库认证)
├── user_util.py # 用户管理工具(管理员专用)
├── requirements.txt # Python 依赖
├── config.json # 配置文件(API密钥+数据库配置)
├── build_windows.bat # Windows 打包脚本
├── build_mac.sh # macOS 打包脚本
└── README.md # 本文件
```
## 技术栈
- **GUI 框架**: Tkinter(Python 内置)
- **图片处理**: Pillow
- **API 客户端**: google-genai
- **数据库**: PyMySQL
- **打包工具**: PyInstaller
## 获取 API 密钥
访问 [Google AI Studio](https://makersuite.google.com/app/apikey) 获取免费的 API 密钥。
## 注意事项
- API 密钥会保存在 `config.json` 文件中,请妥善保管
- 使用 API 可能会产生费用,请查看 Google AI 的定价信息
- 生成高分辨率图片(4K)需要更多时间和 API 配额
## 故障排查
### 登录相关问题
**无法登录 / 数据库连接失败**
- 检查 `config.json` 中的 `db_config` 配置是否正确
- 确认数据库服务器可访问(检查防火墙/网络)
- 验证数据库用户名和密码是否正确
- 确认表 `nano_banana_users` 已创建
**"未找到数据库配置" 错误**
- 确保 `config.json` 包含 `db_config` 字段
- 参考快速开始章节的配置示例
**"用户名或密码错误" 提示**
- 使用 `python user_util.py list` 查看用户列表
- 确认用户状态为 'active'
- 使用 `user_util.py` 重置密码或创建新用户
**密码不匹配**
- 确保数据库中存储的是 SHA256 哈希值,而非明文密码
- 使用 `user_util.py add` 添加用户,会自动计算哈希
### 配置文件只读错误(macOS/Windows 打包应用)
**问题**: 提示 "read-only file system: config.json"
**原因**: 打包后的应用资源目录是只读的,无法在应用包内写入文件
**解决方案**:
- ✅ 已修复:应用现在会自动将配置保存到用户目录
- macOS: `~/Library/Application Support/ZB100ImageGenerator/config.json`
- Windows: `%APPDATA%\ZB100ImageGenerator\config.json`
- 首次运行会自动创建配置文件夹和文件
### 生成失败
- 检查 API 密钥是否正确
- 检查网络连接是否正常
- 查看错误信息,确认是否超出配额
### 找不到 API 密钥
- 开发模式:检查项目目录下的 `config.json` 文件
- 打包应用:检查用户目录下的配置文件(见上方配置文件位置)
- 手动创建配置文件并添加完整配置(参考快速开始章节)
### 打包失败
- 确保安装了所有依赖:`pip install -r requirements.txt`
- 检查 Python 版本是否符合要求(3.8+)
- Windows: 确保有 `zb100_kehuan.ico` 图标文件(或修改打包脚本移除 `--icon` 参数)
- 注意: `user_util.py` 不应打包进客户端版本(仅管理员使用)
## 技术设计原则
本项目遵循 Linus Torvalds 的设计哲学:
- **简洁至上**: 使用 Tkinter 内置 GUI,避免重型框架
- **零特殊情况**: 统一的错误处理和数据流
- **实用主义**: 直接解决问题,不过度设计
- **清晰数据结构**: 简单的配置管理和图片数据流
## 许可证
MIT License
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['image_generator.py'],
pathex=[],
binaries=[],
datas=[('config.json', '.')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name='ZB100ImageGenerator',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['zb100_kehuan.ico'],
)
#!/bin/bash
# macOS Build Script for Gemini Image Generator
echo "================================"
echo "Building Gemini Image Generator"
echo "================================"
# Check if virtual environment exists
if [ ! -d "venv" ]; then
echo "Creating virtual environment..."
python3 -m venv venv
fi
# Activate virtual environment
echo "Activating virtual environment..."
source venv/bin/activate
# Install dependencies
echo "Installing dependencies..."
pip install --upgrade pip
pip install -r requirements.txt
# Clean previous builds
echo "Cleaning previous builds..."
rm -rf build dist *.spec
# Build executable
echo "Building executable..."
pyinstaller --name="ZB100ImageGenerator" \
--onefile \
--windowed \
--add-data "config.json:." \
image_generator_qt.py
# Check if build was successful
if [ -f "dist/ZB100ImageGenerator.app/Contents/MacOS/ZB100ImageGenerator" ] || [ -f "dist/ZB100ImageGenerator" ]; then
echo "================================"
echo "Build successful!"
echo "Application: dist/ZB100ImageGenerator.app (or dist/ZB100ImageGenerator)"
echo "================================"
else
echo "================================"
echo "Build failed!"
echo "================================"
fi
@echo off
REM Windows Build Script for Gemini Image Generator
echo ================================
echo Building Gemini Image Generator
echo ================================
REM Check if virtual environment exists
if not exist "venv" (
echo Creating virtual environment...
python -m venv venv
)
REM Activate virtual environment
echo Activating virtual environment...
call venv\Scripts\activate.bat
REM Install dependencies
echo Installing dependencies...
pip install --upgrade pip
pip install -r requirements.txt
REM Clean previous builds
echo Cleaning previous builds...
if exist "build" rd /s /q build
if exist "dist" rd /s /q dist
if exist "*.spec" del /q *.spec
REM Build executable
echo Building executable...
pyinstaller --name="ZB100ImageGenerator" ^
--onefile ^
--windowed ^
--icon=zb100_kehuan.ico ^
--add-data "config.json;." ^
image_generator_qt.py
REM Check if build was successful
if exist "dist\ZB100ImageGenerator.exe" (
echo ================================
echo Build successful!
echo Executable: dist\ZB100ImageGenerator.exe
echo ================================
) else (
echo ================================
echo Build failed!
echo ================================
)
pause
@echo off
REM 导出 Windows 环境的精确依赖版本
echo 正在导出依赖版本...
pip freeze | findstr /C:"google-genai" /C:"Pillow" /C:"PyQt5" /C:"pyinstaller" > requirements-lock.txt
echo.
echo 已导出到 requirements-lock.txt
echo 请将此文件复制到 Mac 上使用
echo.
type requirements-lock.txt
pause
#!/usr/bin/env python3
"""
Gemini Image Generator App
Simple 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
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
def hash_password(password: str) -> str:
"""使用 SHA256 哈希密码"""
return hashlib.sha256(password.encode('utf-8')).hexdigest()
class DatabaseManager:
"""数据库连接管理类"""
def __init__(self, db_config):
self.config = db_config
def authenticate(self, username, password):
"""
验证用户凭证
返回: (success: bool, message: str)
"""
try:
# 计算密码哈希
password_hash = hash_password(password)
# 连接数据库
conn = pymysql.connect(
host=self.config['host'],
port=self.config.get('port', 3306),
user=self.config['user'],
password=self.config['password'],
database=self.config['database'],
connect_timeout=5
)
try:
with conn.cursor() as cursor:
# 使用参数化查询防止 SQL 注入
sql = f"SELECT * FROM {self.config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
cursor.execute(sql, (username, password_hash))
result = cursor.fetchone()
if result:
return True, "认证成功"
else:
return False, "用户名或密码错误"
finally:
conn.close()
except pymysql.OperationalError as e:
return False, "无法连接到服务器,请检查网络连接"
except Exception as e:
return False, f"认证失败: {str(e)}"
class LoginWindow:
"""登录窗口类"""
def __init__(self, db_config, last_user="", saved_password_hash=""):
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.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.center_window()
# 设置样式
self.setup_styles()
# 创建UI
self.setup_ui()
# 绑定回车键
self.root.bind('<Return>', lambda e: self.on_login())
# 处理窗口关闭
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
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}')
def setup_styles(self):
"""设置样式"""
style = ttk.Style()
style.theme_use('clam')
bg_color = '#ffffff'
accent_color = '#007AFF'
self.root.configure(bg=bg_color)
style.configure('Login.TButton',
background=accent_color,
foreground='white',
borderwidth=0,
focuscolor='none',
font=('Segoe UI', 10, 'bold'),
padding=(20, 10))
style.map('Login.TButton',
background=[('active', '#0051D5'), ('pressed', '#0051D5')])
def setup_ui(self):
"""创建登录界面"""
# 主容器
main_frame = ttk.Frame(self.root, padding=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 = ttk.Frame(main_frame)
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)
self.username_entry.pack(fill="x", ipady=8, pady=(5, 0))
self.username_entry.insert(0, self.last_user)
# 密码
password_frame = ttk.Frame(main_frame)
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='*')
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 = ttk.Frame(main_frame)
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))
# 焦点设置
if self.last_user:
self.password_entry.focus()
else:
self.username_entry.focus()
def on_password_change(self, event):
"""监听密码框变化"""
if not self.password_changed and self.saved_password_hash:
# 首次修改密码,清空占位符
self.password_entry.delete(0, tk.END)
self.password_entry.config(fg='#000000')
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)}")
# 验证输入
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()
# 判断使用保存的密码还是新输入的密码
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)
# 直接使用哈希值进行数据库验证
try:
print(f"[DEBUG] 开始连接数据库: {self.db_config['host']}")
conn = pymysql.connect(
host=self.db_config['host'],
port=self.db_config.get('port', 3306),
user=self.db_config['user'],
password=self.db_config['password'],
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()
else:
print("[DEBUG] 用户名或密码错误")
self.show_error("用户名或密码错误")
self.password_entry.delete(0, tk.END)
self.password_changed = False
self.login_button.config(state='normal')
finally:
conn.close()
print("[DEBUG] 数据库连接已关闭")
except pymysql.OperationalError as e:
print(f"[DEBUG] 数据库连接失败: {e}")
self.show_error("无法连接到服务器,请检查网络连接")
self.login_button.config(state='normal')
except Exception as e:
print(f"[DEBUG] 认证异常: {e}")
self.show_error(f"认证失败: {str(e)}")
self.login_button.config(state='normal')
def show_error(self, message):
"""显示错误信息"""
self.error_label.config(text=message, fg='#ff3b30')
def on_close(self):
"""处理窗口关闭"""
self.success = False
self.root.quit()
self.root.destroy()
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', ''))
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()
self.api_key = ""
self.uploaded_images = [] # List of (file_path, PhotoImage) tuples
self.generated_image_data = None
self.generated_image_bytes = None
self.saved_prompts = [] # Store favorite prompts
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=0,
focuscolor='none',
font=('Segoe UI', 10),
padding=(18, 8))
style.map('Accent.TButton',
background=[('active', hover_color), ('pressed', hover_color)],
foreground=[('disabled', '#999999')])
# Secondary button style
style.configure('Secondary.TButton',
background=secondary_bg,
foreground=text_color,
borderwidth=1,
relief='flat',
font=('Segoe UI', 9),
padding=(12, 6))
style.map('Secondary.TButton',
background=[('active', '#e8e8e8'), ('pressed', '#d8d8d8')])
# Icon button style (small, subtle)
style.configure('Icon.TButton',
background=bg_color,
foreground='#666666',
borderwidth=0,
font=('Segoe UI', 9),
padding=(4, 4))
style.map('Icon.TButton',
background=[('active', secondary_bg)],
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))
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
config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
elif system == 'Windows':
config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
else: # Linux and others
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
def get_config_path(self):
"""Get the full path to config.json"""
return self.get_config_dir() / 'config.json'
def load_config(self):
"""Load API key, saved prompts, and db config from config file"""
config_path = self.get_config_path()
# 初始化默认值
self.db_config = None
self.last_user = ""
# Try to load from user config first
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
self.api_key = config.get("api_key", "")
self.saved_prompts = config.get("saved_prompts", [])
self.db_config = config.get("db_config")
self.last_user = config.get("last_user", "")
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():
with open(bundled_config, 'r', encoding='utf-8') as f:
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密钥或手动编辑配置文件")
def save_config(self, last_user=None):
"""Save configuration to file"""
config_path = self.get_config_path()
try:
config = {
"api_key": self.api_key,
"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'):
config["last_user"] = self.last_user
else:
config["last_user"] = ""
# 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}")
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))
# 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.save_prompt,
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)
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 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", "一幅美丽的风景画,有山有湖,日落时分")
# 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, 12))
# Model
ttk.Label(settings_container, text="AI 模型", foreground='#666666').pack(anchor="w", pady=(0, 4))
self.model = ttk.Combobox(settings_container, width=18, state="readonly")
self.model['values'] = ("gemini-3-pro-image-preview")
self.model.current(0)
self.model.pack(fill="x", pady=(0, 0))
# 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'):
try:
widget.configure(padding=(18, 8))
except:
pass
widget.bind('<Enter>', on_enter)
widget.bind('<Leave>', on_leave)
def update_saved_prompts_list(self):
"""Update the saved prompts dropdown"""
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'] = []
def save_prompt(self):
"""Save current prompt to favorites"""
prompt = self.prompt_text.get("1.0", tk.END).strip()
if not prompt:
self.status_label.config(text="● 提示词不能为空", foreground='#FF3B30')
return
if prompt in self.saved_prompts:
self.status_label.config(text="● 该提示词已收藏", foreground='#FF9500')
self.save_prompt_btn.config(text="✓ 已收藏")
# 2秒后恢复按钮文本
self.root.after(2000, lambda: self.save_prompt_btn.config(text="⭐ 收藏"))
return
self.saved_prompts.append(prompt)
self.save_config()
self.update_saved_prompts_list()
self.status_label.config(text="● 已收藏提示词", foreground='#34C759')
self.save_prompt_btn.config(text="✓ 已收藏")
# 2秒后恢复按钮文本
self.root.after(2000, lambda: self.save_prompt_btn.config(text="⭐ 收藏"))
def load_saved_prompt(self, event):
"""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')
def delete_saved_prompt(self):
"""Delete the currently selected saved prompt"""
index = self.saved_prompts_combo.current()
if index < 0 or index >= len(self.saved_prompts):
self.status_label.config(text="● 请先选择要删除的提示词", foreground='#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')
def upload_images(self):
"""Upload reference images with preview"""
files = filedialog.askopenfilenames(
title="选择参考图片",
filetypes=[("图片文件", "*.png *.jpg *.jpeg *.gif *.bmp"), ("所有文件", "*.*")]
)
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:
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')
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 generate_image(self):
"""Generate image using Gemini API"""
prompt = self.prompt_text.get("1.0", tk.END).strip()
if not prompt:
self.root.after(0, lambda: messagebox.showerror("错误", "请输入图片描述!"))
return
if not self.api_key:
self.root.after(0, lambda: messagebox.showerror("错误", "未找到API密钥,请在config.json中配置!"))
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"))
try:
client = genai.Client(api_key=self.api_key)
# Build content parts
content_parts = [prompt]
# 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'):
mime_type = "image/jpeg"
content_parts.append(
types.Part.from_bytes(
data=base64.b64decode(img_data),
mime_type=mime_type
)
)
# Generation config - using snake_case field names
config = types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=self.aspect_ratio.get(),
image_size=self.image_size.get()
)
)
# Generate
response = client.models.generate_content(
model=self.model.get(),
contents=content_parts,
config=config
)
# Extract image - Fixed for proper data handling
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')
else:
self.generated_image_data = part.inline_data.data
self.generated_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'))
return
raise Exception("响应中没有图片数据")
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
file_path = filedialog.asksaveasfilename(
defaultextension=".png",
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)}")
def main():
# 首先加载配置以获取数据库信息
config_dir = Path('.')
if getattr(sys, 'frozen', False):
system = platform.system()
if system == 'Darwin':
config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
elif system == 'Windows':
config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
else:
config_dir = Path.home() / '.config' / 'zb100imagegenerator'
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / 'config.json'
db_config = None
last_user = ""
saved_password_hash = ""
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
db_config = config.get("db_config")
last_user = config.get("last_user", "")
saved_password_hash = config.get("saved_password_hash", "")
except Exception as e:
print(f"Failed to load config: {e}")
# 如果没有数据库配置,显示错误并退出
if not db_config:
root = tk.Tk()
root.withdraw()
messagebox.showerror("配置错误",
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()
# 如果登录失败,退出应用
if not success:
return
# 保存/清除 last_user 和密码哈希
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_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}")
# 登录成功,启动主应用
root = tk.Tk()
app = ImageGeneratorApp(root)
root.mainloop()
if __name__ == "__main__":
main()
# Qt GUI 版本依赖
# 核心依赖
google-genai>=1.0.0,<2.0.0
Pillow>=10.0.0,<11.0.0
PyQt5>=5.15.0,<6.0.0
# 数据库依赖
pymysql>=1.0.0,<2.0.0
# 打包工具
pyinstaller>=6.0.0,<7.0.0
#!/bin/bash
# Mac 环境设置脚本
echo "================================"
echo "Mac 环境设置 - Qt 版本"
echo "================================"
# 检查 Python 版本
python_version=$(python3 --version 2>&1)
echo "Python 版本: $python_version"
# 创建虚拟环境
if [ ! -d "venv" ]; then
echo "创建虚拟环境..."
python3 -m venv venv
fi
# 激活虚拟环境
echo "激活虚拟环境..."
source venv/bin/activate
# 升级 pip
echo "升级 pip..."
pip install --upgrade pip
# 卸载可能冲突的旧版本
echo "清理旧版本..."
pip uninstall -y google-genai Pillow PyQt5 pyinstaller 2>/dev/null
# 安装依赖
echo "================================"
echo "安装依赖..."
echo "================================"
# 如果有锁定版本文件,优先使用
if [ -f "requirements-lock.txt" ]; then
echo "使用锁定版本 (requirements-lock.txt)..."
pip install -r requirements-lock.txt
else
echo "使用范围版本 (requirements.txt)..."
pip install -r requirements.txt
fi
# 验证安装
echo "================================"
echo "验证安装..."
echo "================================"
pip list | grep -E "google-genai|Pillow|PyQt5|pyinstaller"
echo "================================"
echo "设置完成!"
echo "================================"
echo ""
echo "运行应用: python3 image_generator_qt.py"
echo ""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户管理工具 - 管理员专用
用法:
python user_util.py add <username> <password> # 添加用户
python user_util.py list # 列出用户
python user_util.py disable <username> # 禁用用户
python user_util.py enable <username> # 启用用户
python user_util.py reset <username> <password> # 重置密码
安全提示:
- 此工具仅供管理员使用,请勿分发给用户
- 避免在命令行直接输入密码(可被 shell 历史记录)
- 建议使用环境变量或交互式输入密码
"""
import hashlib
import pymysql
import json
import sys
import os
from pathlib import Path
# Windows 控制台编码修复
if sys.platform == 'win32':
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
def hash_password(password: str) -> str:
"""使用 SHA256 哈希密码"""
return hashlib.sha256(password.encode('utf-8')).hexdigest()
class UserManager:
"""用户管理类"""
def __init__(self, db_config):
self.config = db_config
def add_user(self, username, password):
"""添加新用户"""
hashed = hash_password(password)
conn = None
try:
conn = pymysql.connect(
host=self.config['host'],
port=self.config.get('port', 3306),
user=self.config['user'],
password=self.config['password'],
database=self.config['database'],
connect_timeout=5
)
with conn.cursor() as cursor:
sql = f"INSERT INTO {self.config['table']} (user_name, passwd, status) VALUES (%s, %s, %s)"
cursor.execute(sql, (username, hashed, 'active'))
conn.commit()
print(f"✓ 用户 '{username}' 添加成功")
print(f" 密码哈希: {hashed[:16]}...")
except pymysql.IntegrityError:
print(f"✗ 用户 '{username}' 已存在")
except pymysql.OperationalError as e:
print(f"✗ 数据库连接失败: {e}")
except Exception as e:
print(f"✗ 添加用户失败: {e}")
finally:
if conn:
conn.close()
def list_users(self):
"""列出所有用户"""
conn = None
try:
conn = pymysql.connect(
host=self.config['host'],
port=self.config.get('port', 3306),
user=self.config['user'],
password=self.config['password'],
database=self.config['database'],
connect_timeout=5
)
with conn.cursor() as cursor:
sql = f"SELECT user_name, passwd, status FROM {self.config['table']}"
cursor.execute(sql)
results = cursor.fetchall()
if not results:
print("没有找到任何用户")
return
# 打印表格
print("\n用户列表:")
print(" ┌────────────────────────┬──────────┬──────────────────┐")
print(" │ 用户名 │ 状态 │ 密码哈希(前8位) │")
print(" ├────────────────────────┼──────────┼──────────────────┤")
for row in results:
username = row[0] or ""
passwd_hash = row[1] or ""
status = row[2] or "NULL"
# 填充空格使对齐
username_display = username[:20].ljust(20)
status_display = status[:8].ljust(8)
hash_display = passwd_hash[:16] if passwd_hash else "N/A".ljust(16)
print(f" │ {username_display} │ {status_display} │ {hash_display} │")
print(" └────────────────────────┴──────────┴──────────────────┘")
print(f"\n总计: {len(results)} 个用户\n")
except pymysql.OperationalError as e:
print(f"✗ 数据库连接失败: {e}")
except Exception as e:
print(f"✗ 查询用户失败: {e}")
finally:
if conn:
conn.close()
def disable_user(self, username):
"""禁用用户"""
self._update_user_status(username, 'disabled', "已禁用")
def enable_user(self, username):
"""启用用户"""
self._update_user_status(username, 'active', "已启用")
def _update_user_status(self, username, status, action_name):
"""更新用户状态"""
conn = None
try:
conn = pymysql.connect(
host=self.config['host'],
port=self.config.get('port', 3306),
user=self.config['user'],
password=self.config['password'],
database=self.config['database'],
connect_timeout=5
)
with conn.cursor() as cursor:
sql = f"UPDATE {self.config['table']} SET status=%s WHERE user_name=%s"
affected = cursor.execute(sql, (status, username))
if affected > 0:
conn.commit()
print(f"✓ 用户 '{username}' {action_name}")
else:
print(f"✗ 用户 '{username}' 不存在")
except pymysql.OperationalError as e:
print(f"✗ 数据库连接失败: {e}")
except Exception as e:
print(f"✗ 更新用户状态失败: {e}")
finally:
if conn:
conn.close()
def reset_password(self, username, new_password):
"""重置用户密码"""
hashed = hash_password(new_password)
conn = None
try:
conn = pymysql.connect(
host=self.config['host'],
port=self.config.get('port', 3306),
user=self.config['user'],
password=self.config['password'],
database=self.config['database'],
connect_timeout=5
)
with conn.cursor() as cursor:
sql = f"UPDATE {self.config['table']} SET passwd=%s WHERE user_name=%s"
affected = cursor.execute(sql, (hashed, username))
if affected > 0:
conn.commit()
print(f"✓ 用户 '{username}' 密码已重置")
print(f" 新密码哈希: {hashed[:16]}...")
else:
print(f"✗ 用户 '{username}' 不存在")
except pymysql.OperationalError as e:
print(f"✗ 数据库连接失败: {e}")
except Exception as e:
print(f"✗ 重置密码失败: {e}")
finally:
if conn:
conn.close()
def load_db_config():
"""从 config.json 加载数据库配置"""
config_path = Path('config.json')
if not config_path.exists():
print(f"✗ 配置文件不存在: {config_path}")
print(f" 请确保在项目目录下运行此工具")
return None
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
db_config = config.get('db_config')
if not db_config:
print("✗ 配置文件中未找到 db_config 字段")
return None
required_fields = ['host', 'user', 'password', 'database', 'table']
missing = [f for f in required_fields if f not in db_config]
if missing:
print(f"✗ db_config 缺少必需字段: {', '.join(missing)}")
return None
return db_config
except json.JSONDecodeError:
print(f"✗ 配置文件格式错误: {config_path}")
return None
except Exception as e:
print(f"✗ 加载配置失败: {e}")
return None
def print_help():
"""打印帮助信息"""
print(__doc__)
def main():
"""主函数"""
if len(sys.argv) < 2:
print_help()
sys.exit(1)
command = sys.argv[1].lower()
# 加载数据库配置
db_config = load_db_config()
if not db_config:
sys.exit(1)
manager = UserManager(db_config)
# 处理命令
if command == 'add':
if len(sys.argv) != 4:
print("用法: python user_util.py add <username> <password>")
sys.exit(1)
username = sys.argv[2]
password = sys.argv[3]
manager.add_user(username, password)
elif command == 'list':
manager.list_users()
elif command == 'disable':
if len(sys.argv) != 3:
print("用法: python user_util.py disable <username>")
sys.exit(1)
username = sys.argv[2]
manager.disable_user(username)
elif command == 'enable':
if len(sys.argv) != 3:
print("用法: python user_util.py enable <username>")
sys.exit(1)
username = sys.argv[2]
manager.enable_user(username)
elif command == 'reset':
if len(sys.argv) != 4:
print("用法: python user_util.py reset <username> <password>")
sys.exit(1)
username = sys.argv[2]
new_password = sys.argv[3]
manager.reset_password(username, new_password)
else:
print(f"✗ 未知命令: {command}")
print_help()
sys.exit(1)
if __name__ == '__main__':
main()
No preview for this file type