fix:api_key设置为从环境变量获取

This commit is contained in:
dzy1128
2025-12-01 16:33:05 +08:00
parent 0b56c63b60
commit c40a9e8bf0
7 changed files with 353 additions and 589 deletions
+1
View File
@@ -1,5 +1,6 @@
# Configuration files with API keys
config.py
.env
# Python cache
__pycache__/
-135
View File
@@ -1,135 +0,0 @@
# 性能优化总结
## ✅ 已完成的优化
### 1. 🚀 图片压缩优化(最重要)
#### 优化内容:
- ✅ **自动缩放**:限制最大尺寸为 2048px
- ✅ **格式统一**:全部使用 JPEG 格式(比 PNG 小 70-90%)
- ✅ **质量优化**:设置为 85%(人眼几乎无法察觉差异)
- ✅ **优化标志**:启用 JPEG optimize 参数
#### 预期效果:
```
优化前:一张 4000x3000 的图片
- 文件大小:3-5 MB
- 编码时间:2-3 秒
- Base64 后:4-7 MB
优化后:相同图片
- 调整到:2048x1536
- 文件大小:200-300 KB (减少 90%)
- 编码时间:0.1-0.2 秒 (快 10-15 倍)
- Base64 后:300-400 KB
```
### 2. ⏱️ 精确的时间统计
- **只统计 API 请求时间**,不包含本地处理
- 与网站显示时间一致
### 3. 📊 详细的日志输出
每次运行会显示:
```
[VectorEngine] Processing 2 input images...
[VectorEngine] Image 1: encoded in 0.15s, size: 245.3KB
[VectorEngine] Image 2: encoded in 0.12s, size: 189.7KB
[VectorEngine] Sending request to API (payload size: 0.58MB)...
[VectorEngine] API request completed in 26.34s
```
## 📈 性能提升预估
### 场景 1:2张大图 (各 4000x3000)
| 阶段 | 优化前 | 优化后 | 提升 |
|------|--------|--------|------|
| 图片编码 | 5-6 秒 | 0.3-0.4 秒 | **快 15 倍** |
| 数据上传 | 10-15 秒 | 1-2 秒 | **快 7-10 倍** |
| API 生成 | 26 秒 | 26 秒 | 相同 |
| 响应下载 | 2-3 秒 | 2-3 秒 | 相同 |
| **总耗时** | **43-50 秒** | **29-31 秒** | **快 40-50%** |
### 场景 2:1张小图 (1024x768)
| 阶段 | 优化前 | 优化后 | 提升 |
|------|--------|--------|------|
| 图片编码 | 0.5 秒 | 0.05 秒 | **快 10 倍** |
| 数据上传 | 2-3 秒 | 0.3-0.5 秒 | **快 6 倍** |
| API 生成 | 26 秒 | 26 秒 | 相同 |
| **总耗时** | **28-30 秒** | **26-27 秒** | **快 7-10%** |
## 🎯 最大的性能瓶颈
现在的主要耗时:
1. **API 生成时间**:26 秒左右(无法优化,由服务器决定)
2. **网络传输**:已优化到最小
3. **本地处理**:已优化到几乎可以忽略
## 💡 进一步优化建议
### 如果还是觉得慢,可以:
1. **降低输出分辨率**
```
image_size: 4K → 2K → 1K
生成速度会更快
```
2. **减少输入图片数量**
```
5张图片 → 2-3张
编码和上传时间减少
```
3. **调整压缩参数**(修改代码第 152 行)
```python
# 更激进的压缩(更快,质量略低)
base64_data, mime_type = self.tensor_to_base64(img, max_size=1536, quality=75)
# 当前设置(推荐)
base64_data, mime_type = self.tensor_to_base64(img, max_size=2048, quality=85)
```
4. **网络优化**
- 使用更快的网络连接
- 有线连接比 WiFi 更稳定
## ⚙️ 优化参数说明
当前节点使用的参数:
```python
max_size = 2048 # 图片最大边长
quality = 85 # JPEG 质量 (0-100)
format = "JPEG" # 图片格式
optimize = True # JPEG 优化
```
### 参数建议:
| 场景 | max_size | quality | 说明 |
|------|----------|---------|------|
| **测试/预览** | 1536 | 75 | 最快速度 |
| **日常使用** ⭐ | 2048 | 85 | 平衡推荐 |
| **高质量** | 4096 | 95 | 最佳质量 |
## 📝 总结
### 已解决的问题:
✅ 图片编码太慢 → 快 10-15 倍
✅ 数据传输太慢 → 文件小 90%
✅ 时间统计不准 → 只统计 API 时间
✅ 不知道进度 → 添加详细日志
### 无法解决的限制:
⏳ API 生成时间(由服务器决定,约 26 秒)
⏳ 网络延迟(取决于网络质量)
### 实际效果:
对于典型的 2-3 张图片生成场景,**总耗时可以从 45-60 秒缩短到 28-32 秒**,提升约 **40-50%**!
主要的剩余时间都是**真实的 API 生成时间**,这个是无法优化的。
-164
View File
@@ -1,164 +0,0 @@
# Performance Optimization Guide
## 已实现的优化
### 1. 🖼️ 智能图片压缩
**优化前:**
- 直接将原始图片转换为 PNG/JPEG
- 没有尺寸限制
- PNG 格式文件很大
- 大图片传输缓慢
**优化后:**
- ✅ 自动调整图片尺寸(最大 2048px)
- ✅ 统一使用 JPEG 格式(更好的压缩率)
- ✅ 质量设置为 85%(视觉质量和文件大小的最佳平衡)
- ✅ 启用优化标志(optimize=True)
**预期效果:**
- 文件大小减少 **70-90%**
- 上传时间减少 **70-90%**
- 对生成质量几乎无影响
### 2. ⏱️ 精确的时间统计
**优化前:**
- 时间统计包含所有本地处理时间
- 显示时间远超实际 API 生成时间
**优化后:**
- ✅ 只统计真实的 API 请求时间
- ✅ 不包含图片编码/解码时间
- ✅ 与网站显示时间一致
### 3. 📊 详细的进度日志
**新增功能:**
- ✅ 显示每张图片的编码时间
- ✅ 显示压缩后的文件大小
- ✅ 显示 API 请求的 payload 大小
- ✅ 显示 API 响应时间
**日志示例:**
```
[VectorEngine] Processing 2 input images...
[VectorEngine] Image 1: encoded in 0.15s, size: 245.3KB
[VectorEngine] Image 2: encoded in 0.12s, size: 189.7KB
[VectorEngine] Sending request to API (payload size: 0.58MB)...
[VectorEngine] API request completed in 26.34s
```
## 性能对比
### 示例:2张高分辨率图片 (4000x3000)
| 指标 | 优化前 | 优化后 | 提升 |
|------|--------|--------|------|
| 单张图片大小 | ~3-5 MB | ~200-300 KB | **90%↓** |
| 编码时间 | ~2-3 秒/张 | ~0.1-0.2 秒/张 | **90%↓** |
| 上传时间 | ~10-15 秒 | ~1-2 秒 | **85%↓** |
| 总体耗时 | ~45-60 秒 | ~28-32 秒 | **40-50%↓** |
## 优化参数说明
### 当前配置
```python
max_size = 2048 # 最大尺寸 2048px
quality = 85 # JPEG 质量 85%
format = "JPEG" # 统一使用 JPEG
optimize = True # 启用优化
```
### 如何调整
如果需要自定义优化参数,可以修改 `vector_engine_node.py` 第 152 行:
```python
# 更高质量(更慢)
base64_data, mime_type = self.tensor_to_base64(img, max_size=4096, quality=95)
# 更快速度(质量略低)
base64_data, mime_type = self.tensor_to_base64(img, max_size=1536, quality=75)
# 默认平衡(推荐)
base64_data, mime_type = self.tensor_to_base64(img, max_size=2048, quality=85)
```
## 参数推荐
### 质量优先
```python
max_size = 4096
quality = 95
```
- 适合:需要最高质量
- 缺点:处理时间较长
### 平衡模式(默认)
```python
max_size = 2048
quality = 85
```
- 适合:大多数使用场景
- 优点:质量和速度的最佳平衡
### 速度优先
```python
max_size = 1536
quality = 75
```
- 适合:快速测试、预览
- 优点:最快的处理速度
## 网络优化建议
1. **使用稳定的网络连接**
- API 请求需要良好的网络
- 考虑使用有线网络
2. **批量处理**
- 一次处理多张图片比分开处理更高效
3. **合理选择分辨率**
- 1K: 最快,适合测试
- 2K: 平衡,推荐使用
- 4K: 高质量,较慢
## 故障排查
### 如果仍然很慢
1. **检查日志**
- 查看每个步骤的耗时
- 确定瓶颈在哪里
2. **图片编码慢**
- 降低 `max_size` 到 1536 或 1024
- 降低 `quality` 到 75
3. **API 请求慢**
- 检查网络连接
- 尝试较小的输出分辨率(1K 而非 4K)
4. **payload 太大**
- 减少输入图片数量
- 降低图片质量参数
## 更多优化空间
### 可能的未来优化
1. **异步处理**
- 并行编码多张图片
2. **缓存机制**
- 缓存已编码的图片
3. **连接池**
- 复用 HTTP 连接
4. **流式处理**
- 逐步下载生成的图片
+282 -134
View File
@@ -1,156 +1,304 @@
# ComfyUI Vector Engine Image Generator Node
# ComfyUI Vector Engine 图像生成节点
This is a custom node for ComfyUI that integrates Vector Engine's Gemini API for advanced image generation and editing.
这是一个集成了 Vector Engine Gemini API 的 ComfyUI 自定义节点,用于高级图像生成和编辑。
## Features
## ✨ 功能特点
- 🖼️ Support up to 5 optional input images
- 🎨 Configurable aspect ratios (1:1, 2:3, 3:2, 4:3, 3:4, 16:9, 9:16)
- 📐 Multiple resolution options (1K, 2K, 4K)
- 🎲 Seed control for reproducible results
- 📝 Custom system and user prompts
- ℹ️ Detailed generation information output
- 🖼️ **多图片输入**:支持最多 5 张可选输入图片
- 🎨 **灵活配置**:多种纵横比和分辨率选项
- 🎲 **种子控制**:可设置种子值(用于界面显示,不影响生成)
- 📝 **自定义提示词**:支持系统提示词和用户提示词
- ⚡ **性能优化**:自动压缩图片,大幅提升处理速度
- 📊 **详细信息**:输出生成详情和状态信息
- 💬 **进度日志**:显示实时处理进度
## Installation
## 📦 安装
1. Navigate to your ComfyUI custom_nodes directory:
### 方法 1: 直接复制
1. 将整个文件夹复制到 ComfyUI 的 custom_nodes 目录:
```bash
cd ComfyUI/custom_nodes/
cp -r ComfyUI-Vector-Engine /path/to/ComfyUI/custom_nodes/
```
2. Clone or copy this repository:
2. 重启 ComfyUI
### 方法 2: Git Clone
```bash
cd /path/to/ComfyUI/custom_nodes/
git clone <repository-url> ComfyUI-Vector-Engine
# or copy the folder manually
```
3. Restart ComfyUI
## Node Inputs
### Required Parameters
- **prompt** (STRING, multiline): User prompt describing what to generate
- Default: "Generate a creative image based on the provided pictures."
- **system_prompt** (STRING, multiline): System instructions for the AI
- Default: "You are an AI assistant skilled in generating images and editing pictures."
- **aspect_ratio** (DROPDOWN): Image aspect ratio
- Options: 1:1, 2:3, 3:2, 4:3, 3:4, 16:9, 9:16
- Default: 1:1
- **image_size** (DROPDOWN): Output resolution
- Options: 1K, 2K, 4K
- Default: 1K
- **seed** (INT): Random seed for reproducibility
- Range: 0 to max int
- Default: 0
### Optional Parameters
- **image_1** to **image_5** (IMAGE): Up to 5 optional input images
- All images are optional, you can use 0 to 5 images
## Node Outputs
1. **image** (IMAGE): The generated image tensor
- Can be connected to Preview Image, Save Image, or other image processing nodes
2. **info** (STRING): Generation information including:
- Model name
- Aspect ratio
- Image size
- Actual resolution
- Seed value
- Number of input images
- Generation time
- Success/failure status
- Error message (if failed)
## Usage Examples
### Example 1: Generate from Text Only
```
1. Add "Vector Engine Image Generator" node
2. Set prompt: "A beautiful sunset over mountains"
3. Leave all image inputs empty
4. Connect output to "Preview Image"
5. Run the workflow
```
### Example 2: Edit/Combine Multiple Images
```
1. Load 2-5 images using "Load Image" nodes
2. Add "Vector Engine Image Generator" node
3. Connect images to image_1, image_2, etc.
4. Set prompt: "Combine these people in a group photo at the beach"
5. Connect output to "Save Image"
6. Run the workflow
```
### Example 3: Generate with Specific Aspect Ratio
```
1. Add "Vector Engine Image Generator" node
2. Set aspect_ratio: "16:9"
3. Set image_size: "2K"
4. Set prompt: "A cinematic landscape photo"
5. Run the workflow
```
## Configuration
The API key is currently hardcoded in the node. To change it:
1. Open `vector_engine_node.py`
2. Find the line: `self.api_key = "sk-..."`
3. Replace with your API key
For production use, consider using environment variables:
```python
import os
self.api_key = os.getenv("VECTOR_ENGINE_API_KEY", "default-key")
```
## Model Information
- **Current Model**: gemini-3-pro-image-preview
- **API Endpoint**: api.vectorengine.ai
- **Features**: Text-to-image and image-to-image generation
## Troubleshooting
### No image generated (black output)
- Check the info output for error messages
- Verify your API key is valid
- Check network connectivity
- Ensure input images are in correct format
### Image quality issues
- Try increasing image_size (1K → 2K → 4K)
- Adjust aspect_ratio to match desired output
- Refine your prompt for better results
### Slow generation
- Higher resolutions (4K) take longer
- Multiple input images increase processing time
- Check your network connection
## Dependencies
### 依赖项
节点依赖以下库(ComfyUI 默认已包含):
- torch
- numpy
- PIL (Pillow)
- Standard Python libraries (http.client, json, base64, time, io)
- 标准库:http.client, json, base64, time, io
These should already be available in a standard ComfyUI installation.
## 🎮 使用方法
## License
### 节点输入
[Add your license information here]
#### 必选参数
## Support
| 参数 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| **prompt** | 文本 | 用户提示词,描述要生成的内容 | "Generate a creative image..." |
| **system_prompt** | 文本 | 系统提示词,指导 AI 行为 | "You are an AI assistant..." |
| **aspect_ratio** | 下拉菜单 | 图片纵横比 | 1:1 |
| **image_size** | 下拉菜单 | 输出分辨率 | 1K |
| **seed** | 整数 | 种子值(仅显示用) | 0 |
For issues and questions, please open an issue on the repository.
**纵横比选项**:
- 1:1 (正方形)
- 2:3, 3:2 (标准照片)
- 4:3, 3:4 (传统屏幕)
- 16:9, 9:16 (宽屏/竖屏)
**分辨率选项**:
- 1K - 快速生成
- 2K - 平衡质量(推荐)
- 4K - 高质量(较慢)
#### 可选参数
| 参数 | 类型 | 说明 |
|------|------|------|
| **image_1 ~ image_5** | 图片 | 最多 5 张可选输入图片 |
### 节点输出
| 输出 | 类型 | 说明 |
|------|------|------|
| **image** | IMAGE | 生成的图片(可连接 Preview Image / Save Image) |
| **info** | STRING | 生成信息(模型、分辨率、耗时、状态等) |
### 信息输出示例
```
==============================================================
Vector Engine Image Generation Result
==============================================================
Model Name: gemini-3-pro-image-preview
Aspect Ratio: 2:3
Image Size: 2K
Resolution: 1024x1536
Seed: 12345
Input Images: 2
Generation Time: 26.34s
Status: SUCCESS
==============================================================
```
## 📝 使用示例
### 示例 1:纯文本生成
```
1. 添加 "Vector Engine Image Generator" 节点
2. 设置 prompt: "A beautiful sunset over mountains"
3. 不连接任何输入图片
4. 连接输出到 "Preview Image"
5. 执行工作流
```
### 示例 2:图片编辑/合成
```
1. 使用 "Load Image" 加载 2-3 张图片
2. 添加 "Vector Engine Image Generator" 节点
3. 连接图片到 image_1, image_2 等
4. 设置 prompt: "Combine these people in a group photo at the beach"
5. 设置 aspect_ratio: "16:9"
6. 连接输出到 "Save Image"
7. 执行工作流
```
### 示例 3:控制纵横比
```
1. 添加节点
2. 设置 aspect_ratio: "16:9" (宽屏)
3. 设置 image_size: "2K"
4. 设置 prompt: "A cinematic landscape with dramatic lighting"
5. 执行工作流
```
## ⚡ 性能优化
节点已内置自动优化:
### 自动图片压缩
- ✅ 自动调整图片尺寸(最大 2048px)
- ✅ 使用 JPEG 格式压缩(质量 85%)
- ✅ 文件大小减少约 90%
- ✅ 编码速度提升 10-15 倍
### 日志输出
运行时会在控制台显示处理进度:
```
[VectorEngine] Processing 2 input images...
[VectorEngine] Image 1: encoded in 0.15s, size: 245.3KB
[VectorEngine] Image 2: encoded in 0.12s, size: 189.7KB
[VectorEngine] Sending request to API (payload size: 0.58MB)...
[VectorEngine] API request completed in 26.34s
```
### 性能数据
**典型场景(2张 4000x3000 图片):**
- 图片编码:~0.3 秒
- 数据上传:~1-2 秒
- API 生成:~26 秒
- **总耗时:~28-30 秒**
## ⚙️ 配置
### API Key 配置
**重要**:节点从环境变量读取 API Key,需要设置 `VECTOR_ENGINE_API_KEY` 环境变量。
#### Linux / macOS
**临时设置(仅当前终端):**
```bash
export VECTOR_ENGINE_API_KEY="sk-your-api-key-here"
```
**永久设置(推荐):**
1. 编辑 `~/.bashrc` 或 `~/.zshrc`:
```bash
echo 'export VECTOR_ENGINE_API_KEY="sk-your-api-key-here"' >> ~/.bashrc
source ~/.bashrc
```
2. 或者在启动 ComfyUI 前设置:
```bash
export VECTOR_ENGINE_API_KEY="sk-your-api-key-here"
python main.py
```
#### Windows
**临时设置(仅当前命令行):**
```cmd
set VECTOR_ENGINE_API_KEY=sk-your-api-key-here
```
**永久设置:**
```cmd
setx VECTOR_ENGINE_API_KEY "sk-your-api-key-here"
```
#### Docker / 容器环境
在 docker-compose.yml 中添加:
```yaml
environment:
- VECTOR_ENGINE_API_KEY=sk-your-api-key-here
```
或使用 docker run:
```bash
docker run -e VECTOR_ENGINE_API_KEY="sk-your-api-key-here" ...
```
#### 验证配置
启动 ComfyUI 后,如果环境变量未设置,节点会抛出错误提示:
```
VECTOR_ENGINE_API_KEY environment variable is not set.
Please set it before using this node.
```
### 自定义压缩参数
如需调整图片压缩设置,修改 `vector_engine_node.py` 第 152 行:
```python
# 默认设置(推荐)
base64_data, mime_type = self.tensor_to_base64(img, max_size=2048, quality=85)
# 更快速度(质量略低)
base64_data, mime_type = self.tensor_to_base64(img, max_size=1536, quality=75)
# 更高质量(较慢)
base64_data, mime_type = self.tensor_to_base64(img, max_size=4096, quality=95)
```
## 🔧 故障排查
### 生成失败(输出黑色图片)
**检查步骤:**
1. 查看 info 输出中的错误信息
2. 确认 API Key 是否有效
3. 检查网络连接
4. 确认输入图片格式正确
**常见错误:**
- `Authentication failed` - API Key 无效
- `Network error` - 网络连接问题
- `No image found` - API 未返回图片
### 生成速度慢
**优化建议:**
1. 降低输出分辨率:4K → 2K → 1K
2. 减少输入图片数量
3. 使用稳定的网络连接
4. 检查日志确定瓶颈
### 图片质量不理想
**改善方法:**
1. 提高输出分辨率:1K → 2K → 4K
2. 调整纵横比匹配需求
3. 优化提示词描述
4. 提供更高质量的输入图片
## 🤖 模型信息
- **当前模型**:gemini-3-pro-image-preview
- **API 端点**:api.vectorengine.ai
- **支持功能**:
- 文本生成图片
- 图片编辑
- 多图片合成
- 风格迁移
## 📄 文件说明
```
ComfyUI-Vector-Engine/
├── vector_engine_node.py # 主节点实现(已优化)
├── __init__.py # 节点注册
├── config.example.py # 配置说明和示例
├── README.md # 完整使用文档(本文件)
├── .gitignore # Git 忽略规则
├── test.py # 测试脚本
└── assets/ # 测试资源(可选)
```
## 🐛 已知限制
1. **种子值**:seed 参数仅用于界面显示,不会传递给 API
2. **生成时间**:API 生成时间约 20-30 秒,无法优化
3. **图片数量**:最多支持 5 张输入图片
4. **模型固定**:当前只支持 gemini-3-pro-image-preview
## 📮 支持与反馈
如遇到问题或有功能建议,请提交 Issue 或 Pull Request。
## 📜 许可证
[请添加许可证信息]
---
**提示**:首次使用建议从 1K 分辨率开始测试,确认工作正常后再使用更高分辨率。
+61 -10
View File
@@ -1,23 +1,74 @@
"""
Configuration file for Vector Engine API
Configuration Example for Vector Engine API
To use:
1. Copy this file to config.py
2. Update with your actual API key
3. Import in vector_engine_node.py
This file shows how to configure the Vector Engine API key.
The actual API key should be set via environment variable for security.
DO NOT hardcode API keys in your code!
"""
# Vector Engine API Configuration
VECTOR_ENGINE_API_KEY = "sk-your-api-key-here"
# ==========================================
# API Key Configuration (RECOMMENDED METHOD)
# ==========================================
# API Endpoint
# Set the environment variable before starting ComfyUI:
#
# Linux/macOS:
# export VECTOR_ENGINE_API_KEY="sk-your-api-key-here"
# python main.py
#
# Windows (CMD):
# set VECTOR_ENGINE_API_KEY=sk-your-api-key-here
# python main.py
#
# Windows (PowerShell):
# $env:VECTOR_ENGINE_API_KEY="sk-your-api-key-here"
# python main.py
# ==========================================
# Permanent Configuration
# ==========================================
# Linux/macOS - Add to ~/.bashrc or ~/.zshrc:
# export VECTOR_ENGINE_API_KEY="sk-your-api-key-here"
#
# Windows - Use setx for permanent environment variable:
# setx VECTOR_ENGINE_API_KEY "sk-your-api-key-here"
# ==========================================
# Docker Configuration
# ==========================================
# In docker-compose.yml:
# environment:
# - VECTOR_ENGINE_API_KEY=sk-your-api-key-here
#
# Or with docker run:
# docker run -e VECTOR_ENGINE_API_KEY="sk-your-api-key-here" ...
# ==========================================
# API Configuration
# ==========================================
# API Endpoint (configured in the node, no need to change)
VECTOR_ENGINE_API_HOST = "api.vectorengine.ai"
# Default Model
# Default Model (configured in the node)
DEFAULT_MODEL = "gemini-3-pro-image-preview"
# Default Generation Config
# Default Generation Settings
DEFAULT_SYSTEM_PROMPT = "You are an AI assistant skilled in generating images and editing pictures."
DEFAULT_ASPECT_RATIO = "1:1"
DEFAULT_IMAGE_SIZE = "1K"
# ==========================================
# Security Notes
# ==========================================
# ✓ DO: Use environment variables for API keys
# ✓ DO: Add sensitive files to .gitignore
# ✓ DO: Use secrets management in production
# ✗ DON'T: Hardcode API keys in code
# ✗ DON'T: Commit API keys to version control
# ✗ DON'T: Share API keys in public repositories
-145
View File
@@ -1,145 +0,0 @@
"""
Performance test script to compare optimization effects
测试脚本:对比优化前后的性能
"""
import base64
import time
from PIL import Image
import io
def test_compression(image_path, max_sizes=[None, 4096, 2048, 1536], qualities=[100, 95, 85, 75]):
"""
Test different compression settings
"""
print(f"\n{'='*70}")
print(f"Testing image: {image_path}")
print(f"{'='*70}\n")
# Load original image
original_img = Image.open(image_path)
if original_img.mode != 'RGB':
original_img = original_img.convert('RGB')
orig_width, orig_height = original_img.size
print(f"Original size: {orig_width}x{orig_height}")
# Get original file size
with open(image_path, 'rb') as f:
original_file_size = len(f.read()) / 1024
print(f"Original file size: {original_file_size:.1f} KB\n")
results = []
for max_size in max_sizes:
for quality in qualities:
# Prepare image
img = original_img.copy()
# Resize if needed
if max_size is not None:
width, height = img.size
if max(width, height) > max_size:
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
resize_start = time.time()
img = img.resize((new_width, new_height), Image.LANCZOS)
resize_time = time.time() - resize_start
else:
new_width, new_height = width, height
resize_time = 0
else:
new_width, new_height = img.size
resize_time = 0
# Compress and encode
buffer = io.BytesIO()
encode_start = time.time()
img.save(buffer, format="JPEG", quality=quality, optimize=True)
encode_time = time.time() - encode_start
img_bytes = buffer.getvalue()
compressed_size_kb = len(img_bytes) / 1024
# Base64 encode
base64_start = time.time()
base64_str = base64.b64encode(img_bytes).decode('utf-8')
base64_time = time.time() - base64_start
base64_size_kb = len(base64_str) / 1024
# Total time
total_time = resize_time + encode_time + base64_time
# Compression ratio
compression_ratio = (1 - compressed_size_kb / original_file_size) * 100 if original_file_size > 0 else 0
result = {
'max_size': max_size or 'Original',
'quality': quality,
'dimensions': f"{new_width}x{new_height}",
'compressed_size_kb': compressed_size_kb,
'base64_size_kb': base64_size_kb,
'total_time': total_time,
'compression_ratio': compression_ratio
}
results.append(result)
print(f"Max Size: {str(max_size or 'Original'):>8} | Quality: {quality:>3}% | "
f"Dimensions: {new_width:>4}x{new_height:<4} | "
f"Size: {compressed_size_kb:>6.1f}KB (base64: {base64_size_kb:>6.1f}KB) | "
f"Time: {total_time:.3f}s | "
f"Compression: {compression_ratio:>5.1f}%")
# Recommend best settings
print(f"\n{'='*70}")
print("Recommendations:")
print(f"{'='*70}")
# Find best balance (around 85% quality, reasonable size)
balanced = [r for r in results if r['quality'] == 85 and r['max_size'] == 2048]
if balanced:
r = balanced[0]
print(f"\n✅ Recommended (Balanced):")
print(f" max_size=2048, quality=85")
print(f" Size: {r['compressed_size_kb']:.1f}KB | Time: {r['total_time']:.3f}s | Compression: {r['compression_ratio']:.1f}%")
# Find fastest
fastest = min(results, key=lambda x: x['total_time'])
print(f"\n⚡ Fastest:")
print(f" max_size={fastest['max_size']}, quality={fastest['quality']}")
print(f" Size: {fastest['compressed_size_kb']:.1f}KB | Time: {fastest['total_time']:.3f}s | Compression: {fastest['compression_ratio']:.1f}%")
# Find best compression
best_compression = max(results, key=lambda x: x['compression_ratio'])
print(f"\n📦 Best Compression:")
print(f" max_size={best_compression['max_size']}, quality={best_compression['quality']}")
print(f" Size: {best_compression['compressed_size_kb']:.1f}KB | Time: {best_compression['total_time']:.3f}s | Compression: {best_compression['compression_ratio']:.1f}%")
print()
if __name__ == "__main__":
# Test with sample images
test_images = [
"./assets/girl.png",
"./assets/boy.jpg",
]
for img_path in test_images:
try:
test_compression(img_path)
except Exception as e:
print(f"Error testing {img_path}: {e}")
print(f"\n{'='*70}")
print("Test Complete!")
print(f"{'='*70}")
print("\nCurrent node settings: max_size=2048, quality=85")
print("This provides the best balance of quality, speed, and file size.")
+9 -1
View File
@@ -2,6 +2,7 @@ import http.client
import json
import base64
import time
import os
import numpy as np
import torch
from PIL import Image
@@ -14,7 +15,14 @@ class VectorEngineImageGenerator:
"""
def __init__(self):
self.api_key = "sk-RZBLe4v8MolmD3fwOd6vdRTCaj7PohDhf4f44UNgWHEAA4zF"
# Read API key from environment variable
self.api_key = os.getenv("VECTOR_ENGINE_API_KEY")
if not self.api_key:
raise ValueError(
"VECTOR_ENGINE_API_KEY environment variable is not set. "
"Please set it before using this node: "
"export VECTOR_ENGINE_API_KEY='your-api-key-here'"
)
@classmethod
def INPUT_TYPES(cls):