Skip to content

Commit 911bddb

Browse files
committed
重写了翻译、扩写、反推,移至后端处理,在保证使用体验的情况下,避免暴露密钥等敏感信息。修复了些bug,优化了提示词
1 parent 27523ad commit 911bddb

File tree

18 files changed

+1172
-1293
lines changed

18 files changed

+1172
-1293
lines changed

__init__.py

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,63 @@
1+
12
import os
23
import re
34
from server import PromptServer
4-
from .server import routes
5+
from . import server
6+
7+
# ANSI颜色常量
8+
GREEN = "\033[92m"
9+
RESET = "\033[0m"
10+
11+
# 模块常量定义
12+
NODE_CLASS_MAPPINGS = {}
13+
NODE_DISPLAY_NAME_MAPPINGS = {}
14+
WEB_DIRECTORY = "./js"
515

6-
# 读取版本号
716
def get_version():
17+
"""
18+
从pyproject.toml文件中读取版本号
19+
20+
Returns:
21+
str: 版本号字符串
22+
23+
Raises:
24+
ValueError: 当无法找到版本号时抛出
25+
"""
826
try:
927
toml_path = os.path.join(os.path.dirname(__file__), "pyproject.toml")
1028
with open(toml_path, "r", encoding='utf-8') as f:
1129
content = f.read()
12-
# 使用正则表达式匹配版本号
1330
version_match = re.search(r'version\s*=\s*"([^"]+)"', content)
1431
if version_match:
1532
return version_match.group(1)
1633
raise ValueError("未在pyproject.toml中找到版本号")
1734
except Exception as e:
1835
print(f"读取版本号失败: {str(e)}")
19-
raise # 直接抛出异常,不提供保底值
20-
21-
# 声明版本号变量
22-
VERSION = get_version()
23-
24-
# 注册节点
25-
NODE_CLASS_MAPPINGS = {}
26-
NODE_DISPLAY_NAME_MAPPINGS = {}
27-
28-
# 设置Web目录
29-
WEB_DIRECTORY = "./js"
36+
raise
3037

31-
# 注册API路由
32-
PromptServer.instance.app.add_routes(routes)
33-
34-
# 将版本号注入到前端全局变量
3538
def inject_version_to_frontend():
36-
# 创建包含版本号的JavaScript代码
39+
"""
40+
将版本号注入到前端全局变量
41+
"""
3742
js_code = f"""
3843
window.PromptAssistant_Version = "{VERSION}";
3944
"""
4045

41-
# 确保js目录存在
4246
js_dir = os.path.join(os.path.dirname(__file__), "js")
4347
if not os.path.exists(js_dir):
4448
os.makedirs(js_dir)
4549

46-
# 写入版本号文件
4750
version_file = os.path.join(js_dir, "version.js")
4851
with open(version_file, "w", encoding='utf-8') as f:
4952
f.write(js_code)
5053

51-
# 执行版本号注入
54+
# 初始化版本号
55+
VERSION = get_version()
56+
57+
# 执行初始化操作
5258
inject_version_to_frontend()
5359

54-
# ANSI颜色代码
55-
GREEN = "\033[92m" # 绿色
56-
RESET = "\033[0m" # 重置颜色
57-
# 打印启动信息,将"已启动"设为绿色
60+
# 打印初始化信息
5861
print(f"✨提示词小助手 V{VERSION} {GREEN}已启动{RESET}")
5962

6063

js/config/system_prompts.json

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,23 @@
22
"expand_prompts": {
33
"ZH": {
44
"role": "system",
5-
"content": "你是一名资深AI绘画提示词专家,请将用户提供的文本内容转换为完整的专业提示词。1.理解用户的文本,在原内容基础上先设定一个主题,再对提示词进行创作扩充。2.扩充的提示词需要包含要素:画面题材、主体细节描述(如:长相特征、服装细节、动作姿态、表情情绪等)、构图方式(如:主体位于画面的位置、比例、画面视角等)、环境描述(例如:场景、背景等)、光影信息(例如:自然光、暗光、逆光、等等)、常用的质量描述(例如:杰作、高画质、丰富细节等)、主题诠释。3.提示词要素围绕主题服务,确保要素的合理性、统一性。避免元素出现不合理、无意义、或生硬的关键词堆砌。4.提示词按主题题材→主体→构图→环境→光影→质量→主题诠释的表述顺序,重新组织内容。5.请直接使用自然语言输出结果,不需要结构化内容(如主题:、题材...)、注释和说明。并控制合理的字数。"
6-
},
7-
"EN": {
8-
"role": "system",
9-
"content": "You are a senior AI art prompt expert. Transform the text provided by users into comprehensive professional prompts. First, understand the user's text, define a theme based on the original content, and then expand and create the prompts. The expanded prompts should include these elements: artwork genre (such as photography, anime, comic, game concept art, 3D rendering, etc.), detailed descriptions of the main subject (including facial features, clothing details, poses, expressions, etc.), composition methods (like the position and proportion of the main subject in the image, viewing angle, etc.), environmental descriptions (such as scenes, backgrounds, etc.), lighting information (such as natural light, low light, backlight, etc.), common quality descriptions (such as masterpiece, high - resolution, rich details, etc.), and an interpretation of the theme. All elements of the prompts should serve the theme, ensuring rationality and consistency, and avoid illogical, meaningless, or forced keyword stacking. Reorganize the content in the order of theme genre → main subject → composition → environment → lighting → quality → theme interpretation. Please directly output the result in natural language, without structured content (like Theme:, Genre: ...), annotations, or explanations, and maintain a reasonable word count."
5+
"content": "你是一名资深AI绘画提示词专家,请根据用户提供的文本内容转换为具有画面题材、主体细节描述(如:长相特征、服装细节、动作姿态、表情情绪等)、画面构图(如:主体位于画面的位置、比例、画面视角等)、环境描述(例如:场景、背景等)、光影信息(例如:自然光、暗光、逆光、等等)、常用的质量描述(例如:杰作、高画质、丰富细节等)的完整提示词。确保提示词要素的合理性、统一性。避免元素出现不合理、无意义、或生硬的关键词堆砌。请直接使用自然语言输出结果,不需要结构化内容(如主题:、题材...)、注释和说明。并控制合理的字数。"
106
}
117
},
128
"translate_prompts": {
13-
"TO_EN": {
14-
"role": "system",
15-
"content": "你是一位专业的AI绘画提示词翻译专家,负责将中文提示词准确翻译成英文。1.保持的格式,不要改变原文的描述结构、书写风格、权重标记格式【如(关键词:1.2)】等。2.翻译需要准确理解全文,使用准确、地道的英文表达词汇。3.准确翻译特定艺术风格、渲染技术等专业术语。4.直接输输出结果,无需注释、说明。"
16-
},
17-
"TO_ZH": {
9+
"ZH": {
1810
"role": "system",
19-
"content": "你是一位专业的AI绘画提示词翻译专家,负责将英文提示词准确翻译成中文。1.保持的格式,不要改变原文的描述结构、书写风格、权重标记格式【如(关键词:1.2)】等。2.翻译需要准确理解全文,使用准确、约定俗成的中文表达词汇。3.准确翻译特定艺术风格、渲染技术等专业术语。4.直接输输出结果,无需注释、说明。"
11+
"content": "你是一名AI绘画领域的提示词翻译专家,负责将用户提供的文本内容由{src_lang}准确地翻译成{dst_lang}。要求:1.完整翻译用户提供的所有文本,不要遗漏;2.保持格式,不要改变原文的书写结构、标点符号、权重标记格式【如(文本内容:1.2)】等;2.准确原文,使用准确、地道的{dst_lang}表达词汇和AI绘画领域的专业的术语;5.直接输出翻译结果,无需注释、说明。"
2012
}
2113
},
2214
"vision_prompts": {
2315
"ZH": {
2416
"role": "system",
25-
"content": "请用简洁的语言对图像进行详细准确的描述,包括画面类型(写实、卡通、抽象、超现实等)、主要元素(人物、动物、物品、场景)的特征及细节、色彩、构图、光影效果等描述信息。注意:不要使用结构化格式,无需注释、说明。"
17+
"content": "请用精炼的语言对画面中的题材、所有元素、元素细节、光影效果、色彩色调、构图等信息进行描述。注意:直接输出描述结果,不要使用结构化书写,无需注释、说明。"
2618
},
2719
"EN": {
2820
"role": "system",
29-
"content": "Please use concise language to provide a detailed and accurate description of the image, including the painting type (realistic, cartoon, abstract, surreal, etc.), the characteristics and details of the main elements (characters, animals, objects, scenes), color, composition, lighting effects and other descriptive information. Note: Do not use a structured format, and no annotations or explanations are needed."
21+
"content": "Please describe the theme, all elements, element details, lighting effects, color tones, composition and other information in the picture in concise language. Note: directly output the description results, do not use structured writing, and no annotations or explanations are needed."
3022
}
3123
}
3224
}

js/modules/PromptAssistant.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ import { EventManager } from "../utils/eventManager.js";
1313
import { ResourceManager } from "../utils/resourceManager.js";
1414
import { UIToolkit } from "../utils/UIToolkit.js";
1515
import { PromptFormatter } from "../utils/promptFormatter.js";
16-
import { BaiduTranslateService } from "../services/baidu.js";
17-
import { llmService } from "../services/llm.js";
16+
import { APIService } from "../services/api.js";
1817

1918
// ====================== 工具函数 ======================
2019

@@ -1190,7 +1189,7 @@ class PromptAssistant {
11901189
);
11911190

11921191
// 调用LLM服务进行扩写
1193-
const result = await llmService.expandPrompt(inputValue, request_id);
1192+
const result = await APIService.llmExpandPrompt(inputValue, request_id);
11941193

11951194
if (result.success) {
11961195
// 更新输入框内容并添加高亮效果
@@ -1335,15 +1334,15 @@ class PromptAssistant {
13351334
try {
13361335
if (translateType === "baidu") {
13371336
// 使用百度翻译服务
1338-
result = await BaiduTranslateService.translate(
1337+
result = await APIService.baiduTranslate(
13391338
inputValue,
13401339
langResult.from,
13411340
langResult.to,
13421341
request_id
13431342
);
13441343
} else {
13451344
// 使用LLM翻译服务
1346-
result = await llmService.translate(
1345+
result = await APIService.llmTranslate(
13471346
inputValue,
13481347
langResult.from,
13491348
langResult.to,

js/modules/imageCaption.js

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { logger } from '../utils/logger.js';
88
import { ResourceManager } from "../utils/resourceManager.js";
99
import { UIToolkit } from "../utils/UIToolkit.js";
1010
import { EventManager } from "../utils/eventManager.js";
11-
import { llmVisionService } from '../services/llm_v.js';
11+
import { APIService } from '../services/api.js';
1212
import { HistoryCacheService } from '../services/cache.js';
1313

1414
// 调试开关
@@ -486,15 +486,49 @@ class ImageCaption {
486486
// 生成请求ID
487487
const request_id = `${node.id}_${Date.now()}`;
488488

489+
// 将图像转换为Base64
490+
console.log("处理图像 - 开始转换为Base64", typeof currentImage, currentImage);
491+
let imageBase64;
492+
try {
493+
imageBase64 = await APIService.imageToBase64(currentImage);
494+
console.log("图像转换成功 - Base64长度:", imageBase64 ? imageBase64.length : 0);
495+
if (!imageBase64) {
496+
throw new Error('图像转换失败');
497+
}
498+
} catch (e) {
499+
console.error("图像转换失败:", e);
500+
throw new Error(`图像转换失败: ${e.message || e}`);
501+
}
502+
503+
// 确保图像数据格式正确
504+
if (typeof imageBase64 !== 'string') {
505+
console.error("图像数据类型错误:", typeof imageBase64);
506+
throw new Error(`图像数据类型错误: ${typeof imageBase64}`);
507+
}
508+
509+
// 确保图像数据是Base64格式
510+
if (!imageBase64.startsWith('data:image')) {
511+
console.log("添加Base64前缀");
512+
imageBase64 = `data:image/jpeg;base64,${imageBase64}`;
513+
}
514+
515+
console.log("发送图像分析请求 - 语言:", lang);
516+
489517
// 调用图像分析服务,传入语言参数
490-
const result = await llmVisionService.analyzeImage(currentImage, request_id, lang);
518+
const result = await APIService.llmAnalyzeImage(imageBase64, lang, request_id);
519+
console.log("图像分析结果:", result);
491520

492-
if (!result.success) {
493-
throw new Error(result.error);
521+
if (!result || !result.success) {
522+
const errorMsg = result?.error || '未知错误';
523+
console.error("图像分析失败:", errorMsg);
524+
throw new Error(errorMsg);
494525
}
495526

496527
// 获取描述文本
497528
const description = result.data.description;
529+
if (!description) {
530+
throw new Error('未获取到图像描述');
531+
}
498532

499533
// 尝试复制到剪贴板
500534
let copySuccess = false;
@@ -584,6 +618,7 @@ class ImageCaption {
584618
}
585619

586620
} catch (error) {
621+
console.error("图像分析最终错误:", error);
587622
logger.error(`图像分析失败: ${error.message}`);
588623

589624
// 获取按钮元素

0 commit comments

Comments
 (0)