@hfyjq/crannia 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/updater.py +229 -40
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +24 -10
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +178 -20
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -1,430 +1,430 @@
|
|
|
1
|
-
"""生图 skill —— 厂商直连(OpenAI 兼容 `/images/generations`)。
|
|
2
|
-
|
|
3
|
-
## 为什么是原生 skill
|
|
4
|
-
|
|
5
|
-
对话模型自己不会画图。这一层把"让另一个服务画"变成一个工具调用:
|
|
6
|
-
描述进去、图出来,而且直接进聊天区(走 `core/artifacts` 那条呈现链,
|
|
7
|
-
不是给用户一段 URL 让他自己点)。
|
|
8
|
-
|
|
9
|
-
## 配置(`data/media_gen_credentials.json`)
|
|
10
|
-
|
|
11
|
-
独立文件,不进 `settings.json`(后者会被设置导入导出带走)::
|
|
12
|
-
|
|
13
|
-
{
|
|
14
|
-
"default": "ark",
|
|
15
|
-
"entries": {
|
|
16
|
-
"ark": {
|
|
17
|
-
"base_url": "https://ark.cn-beijing.volces.com/api/v3",
|
|
18
|
-
"model": "doubao-seedream-4-0-20260415",
|
|
19
|
-
"api_key": "…"
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
- `base_url` 填到那家的 API 根(不一定是 `/v1`:火山是 `/api/v3`);
|
|
25
|
-
- 没配,工具照常注册,调用时回一句"还没配置"(不是崩、也不是假装成功);
|
|
26
|
-
- 密钥一个字都不回显(回执里只出现条目名与模型名)。
|
|
27
|
-
|
|
28
|
-
## 出网
|
|
29
|
-
|
|
30
|
-
两段,都过 `core/security.check_url_egress`(地板):
|
|
31
|
-
|
|
32
|
-
1. 请求厂商 API —— 地址由用户配置给出,必须过闸;
|
|
33
|
-
2. 下载返回的图片 URL —— 每一跳都过闸,且只同站跟随(跨站交回模型,
|
|
34
|
-
与 `§3.10` 同一套判据)。厂商给的 URL 有时效,拿到就下,不存着。
|
|
35
|
-
|
|
36
|
-
## 拿不到的东西
|
|
37
|
-
|
|
38
|
-
- 花费:直连厂商的响应里没有 cost 字段,不做收费通知;
|
|
39
|
-
- 多张:一次一张(各家的 `n` / `sequential_image_generation` 支持不一,
|
|
40
|
-
一套参数打所有模型会撞 400 —— 这是真调时踩过的坑)。
|
|
41
|
-
"""
|
|
42
|
-
|
|
43
|
-
from __future__ import annotations
|
|
44
|
-
|
|
45
|
-
import base64
|
|
46
|
-
import json
|
|
47
|
-
import time
|
|
48
|
-
from pathlib import Path
|
|
49
|
-
from urllib.parse import urlsplit
|
|
50
|
-
|
|
51
|
-
__all__ = ["generate_image"]
|
|
52
|
-
|
|
53
|
-
_TIMEOUT_S = 120.0
|
|
54
|
-
_MAX_HOPS = 3
|
|
55
|
-
|
|
56
|
-
#: 图片字节 → 扩展名(按魔数,不信上游说的 mime)。
|
|
57
|
-
_EXT_BY_MIME = {
|
|
58
|
-
"image/png": ".png",
|
|
59
|
-
"image/jpeg": ".jpg",
|
|
60
|
-
"image/webp": ".webp",
|
|
61
|
-
"image/gif": ".gif",
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def init(security_guard=None) -> None:
|
|
66
|
-
"""装载钩子。不读配置、不发请求 —— 那是每次调用时的事。"""
|
|
67
|
-
return None
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
# 配置
|
|
71
|
-
|
|
72
|
-
def _cred_path() -> Path:
|
|
73
|
-
"""配置文件在哪 —— 以 manifest 的 `settings.storage` 为准。
|
|
74
|
-
|
|
75
|
-
配置文件只有一处口径:界面(`/api/skills/<name>/config`)与本 handler
|
|
76
|
-
读写的必须是同一个文件,否则"界面上改了、模型那边没变"。
|
|
77
|
-
"""
|
|
78
|
-
try:
|
|
79
|
-
from core import skill_settings as _ss
|
|
80
|
-
p = _ss.storage_for("media_gen")
|
|
81
|
-
if p is not None:
|
|
82
|
-
return p
|
|
83
|
-
except Exception: # noqa: BLE001
|
|
84
|
-
pass
|
|
85
|
-
return Path("data") / "media_gen_credentials.json"
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def _load_entries() -> tuple[dict, str]:
|
|
89
|
-
"""`(entries, default)`;读不到/坏文件,空表(调用方给一句实话)。"""
|
|
90
|
-
p = _cred_path()
|
|
91
|
-
if not p.is_file():
|
|
92
|
-
return {}, ""
|
|
93
|
-
try:
|
|
94
|
-
data = json.loads(p.read_text(encoding="utf-8"))
|
|
95
|
-
except Exception as exc: # noqa: BLE001
|
|
96
|
-
print("[media_gen] %s 读不出来:%s: %s" % (p, type(exc).__name__, exc))
|
|
97
|
-
return {}, ""
|
|
98
|
-
if not isinstance(data, dict):
|
|
99
|
-
return {}, ""
|
|
100
|
-
entries = data.get("entries")
|
|
101
|
-
if not isinstance(entries, dict):
|
|
102
|
-
return {}, ""
|
|
103
|
-
clean = {str(k): v for k, v in entries.items() if isinstance(v, dict)}
|
|
104
|
-
return clean, str(data.get("default") or "")
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def _pick_entry(entries: dict, default: str, wanted: str) -> tuple[str, dict] | tuple[str, None]:
|
|
108
|
-
if not entries:
|
|
109
|
-
return "", None
|
|
110
|
-
name = str(wanted or "").strip() or default
|
|
111
|
-
if name and name in entries:
|
|
112
|
-
return name, entries[name]
|
|
113
|
-
if len(entries) == 1:
|
|
114
|
-
only = next(iter(entries))
|
|
115
|
-
return only, entries[only]
|
|
116
|
-
return "", None
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
def _no_config() -> dict:
|
|
120
|
-
return {
|
|
121
|
-
"success": False,
|
|
122
|
-
"error": "还没有配置生图。",
|
|
123
|
-
"hint": ("在 %s 里写一条(base_url / model / api_key),"
|
|
124
|
-
"或者等设置页的「生图与视频」卡片建一条。" % _cred_path()),
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
# HTTP
|
|
129
|
-
|
|
130
|
-
def _client(*, follow_redirects: bool = False):
|
|
131
|
-
"""按当前设置造一个 httpx 客户端(代理跟着设置页那一档走)。"""
|
|
132
|
-
from core import net_proxy as _np
|
|
133
|
-
import httpx
|
|
134
|
-
return _np.httpx_client(httpx.Client, follow_redirects=follow_redirects,
|
|
135
|
-
timeout=_TIMEOUT_S)
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
def _api_url(base_url: str) -> str:
|
|
139
|
-
base = str(base_url or "").strip().rstrip("/")
|
|
140
|
-
return base + "/images/generations"
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
def _same_site(a: str, b: str) -> bool:
|
|
144
|
-
"""同站:scheme + 端口 + 主机(忽略 `www.` 前缀,不吸子域)。"""
|
|
145
|
-
try:
|
|
146
|
-
pa, pb = urlsplit(a), urlsplit(b)
|
|
147
|
-
except ValueError:
|
|
148
|
-
return False
|
|
149
|
-
def norm(p):
|
|
150
|
-
host = (p.hostname or "").lower()
|
|
151
|
-
if host.startswith("www."):
|
|
152
|
-
host = host[4:]
|
|
153
|
-
port = p.port or (443 if (p.scheme or "").lower() == "https" else 80)
|
|
154
|
-
return (p.scheme or "").lower(), port, host
|
|
155
|
-
return norm(pa) == norm(pb)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
def _download_image(url: str, dest: Path) -> str:
|
|
159
|
-
"""把厂商给的 URL 立刻下到文件。返回错误串;成功,空串。
|
|
160
|
-
|
|
161
|
-
每一跳都过 `check_url_egress`(地板),只同站跟随 ——
|
|
162
|
-
跨站跳转不跟,交回模型/用户重来(与 `§3.10` 逐字同一条判据)。
|
|
163
|
-
"""
|
|
164
|
-
from core.security import UrlEgressError, check_url_egress
|
|
165
|
-
|
|
166
|
-
cur = url
|
|
167
|
-
for _hop in range(_MAX_HOPS + 1):
|
|
168
|
-
try:
|
|
169
|
-
cur = check_url_egress(cur)
|
|
170
|
-
except UrlEgressError as exc:
|
|
171
|
-
return "图片地址没通过出网闸:%s" % exc
|
|
172
|
-
try:
|
|
173
|
-
with _client() as c:
|
|
174
|
-
with c.stream("GET", cur) as r:
|
|
175
|
-
if 300 <= r.status_code < 400:
|
|
176
|
-
nxt = r.headers.get("location") or ""
|
|
177
|
-
if not nxt or not _same_site(cur, nxt):
|
|
178
|
-
return ("图片地址跨站跳转了(未跟随)。"
|
|
179
|
-
"让模型重新生成一次,或把它下载到本机后再处理。")
|
|
180
|
-
cur = nxt
|
|
181
|
-
continue
|
|
182
|
-
if r.status_code >= 400:
|
|
183
|
-
return "下载图片失败:HTTP %d" % r.status_code
|
|
184
|
-
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
185
|
-
tmp = dest.with_suffix(dest.suffix + ".part")
|
|
186
|
-
with tmp.open("wb") as f:
|
|
187
|
-
for chunk in r.iter_bytes():
|
|
188
|
-
f.write(chunk)
|
|
189
|
-
tmp.replace(dest)
|
|
190
|
-
return ""
|
|
191
|
-
except Exception as exc: # noqa: BLE001
|
|
192
|
-
return "下载图片失败(%s)。如果是网络问题:设置页的「出网代理」要选对。" % type(exc).__name__
|
|
193
|
-
return "图片地址跳转次数过多(>%d)。" % _MAX_HOPS
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
def _ext_for(data: bytes) -> str:
|
|
197
|
-
"""按魔数给扩展名(上游说的 mime 不是证据)。"""
|
|
198
|
-
try:
|
|
199
|
-
from core import artifacts as _art
|
|
200
|
-
mime = _art.sniff(data) or ""
|
|
201
|
-
except Exception: # noqa: BLE001
|
|
202
|
-
mime = ""
|
|
203
|
-
return _EXT_BY_MIME.get(mime, ".png")
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
def _out_dir() -> Path:
|
|
207
|
-
"""落点:只有一处口径(`core/workspace.primary_output_dir`)。"""
|
|
208
|
-
from core.workspace import primary_output_dir
|
|
209
|
-
d = Path(str(primary_output_dir()))
|
|
210
|
-
d.mkdir(parents=True, exist_ok=True)
|
|
211
|
-
return d
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
def _stamp() -> str:
|
|
215
|
-
return time.strftime("%Y%m%d-%H%M%S")
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
# 工具
|
|
219
|
-
|
|
220
|
-
def generate_image(prompt: str, size: str = "", entry: str = "") -> dict:
|
|
221
|
-
"""生成一张图片并保存到工作区(产出的图会直接显示在聊天里)。"""
|
|
222
|
-
text = str(prompt or "").strip()
|
|
223
|
-
if not text:
|
|
224
|
-
return {"success": False, "error": "prompt 不能为空。"}
|
|
225
|
-
|
|
226
|
-
entries, default = _load_entries()
|
|
227
|
-
name, cfg = _pick_entry(entries, default, entry)
|
|
228
|
-
if cfg is None:
|
|
229
|
-
if not entries:
|
|
230
|
-
return _no_config()
|
|
231
|
-
return {"success": False,
|
|
232
|
-
"error": "没有叫「%s」的配置。" % (entry or default),
|
|
233
|
-
"hint": "可用的条目:%s" % "、".join(sorted(entries))}
|
|
234
|
-
|
|
235
|
-
base_url = str(cfg.get("base_url") or "").strip()
|
|
236
|
-
model = str(cfg.get("model") or "").strip()
|
|
237
|
-
api_key = str(cfg.get("api_key") or "").strip()
|
|
238
|
-
kind = str(cfg.get("type") or "vendor").strip().lower()
|
|
239
|
-
|
|
240
|
-
# 本地后端:协议完全不同(SD WebUI 的 `/sdapi/v1/txt2img`),
|
|
241
|
-
# 而且它不过出网闸 —— 因为它按定义就是本机;但"本机"只能是回环地址,
|
|
242
|
-
# 否则一个配置就能把局域网当成生图服务(那是 SSRF,不是本地接入)。
|
|
243
|
-
if kind == "local":
|
|
244
|
-
return _generate_local(name, cfg, text, size)
|
|
245
|
-
|
|
246
|
-
if not base_url or not model or not api_key:
|
|
247
|
-
missing = [k for k, v in (("base_url", base_url), ("model", model),
|
|
248
|
-
("api_key", api_key)) if not v]
|
|
249
|
-
return {"success": False,
|
|
250
|
-
"error": "配置「%s」缺字段:%s。" % (name, "、".join(missing)),
|
|
251
|
-
"hint": "补在 %s 里(或等设置页那张卡)。" % _cred_path()}
|
|
252
|
-
|
|
253
|
-
body = {"model": model, "prompt": text}
|
|
254
|
-
if str(size or "").strip():
|
|
255
|
-
body["size"] = str(size).strip()
|
|
256
|
-
# 官方示例里 `watermark: true` —— 我们必须显式写 false(不往用户图上盖水印)。
|
|
257
|
-
body["watermark"] = False
|
|
258
|
-
body["response_format"] = "url"
|
|
259
|
-
|
|
260
|
-
try:
|
|
261
|
-
from core.security import UrlEgressError, check_url_egress
|
|
262
|
-
except Exception as exc: # noqa: BLE001
|
|
263
|
-
return {"success": False, "error": "出网闸不可用(%s)。" % type(exc).__name__}
|
|
264
|
-
try:
|
|
265
|
-
api_url = check_url_egress(_api_url(base_url))
|
|
266
|
-
except UrlEgressError as exc:
|
|
267
|
-
return {"success": False, "error": "生图服务地址没通过出网闸:%s" % exc}
|
|
268
|
-
except Exception as exc: # noqa: BLE001
|
|
269
|
-
return {"success": False, "error": "生图服务地址不合法:%s" % exc}
|
|
270
|
-
|
|
271
|
-
try:
|
|
272
|
-
with _client() as c:
|
|
273
|
-
r = c.post(api_url, headers={"Authorization": "Bearer " + api_key,
|
|
274
|
-
"Content-Type": "application/json"},
|
|
275
|
-
json=body)
|
|
276
|
-
except Exception as exc: # noqa: BLE001
|
|
277
|
-
return {"success": False,
|
|
278
|
-
"error": "连不上生图服务(%s)。" % type(exc).__name__,
|
|
279
|
-
"hint": "如果是网络问题:设置页的「出网代理」要选对(system / manual)。"}
|
|
280
|
-
|
|
281
|
-
if r.status_code == 401:
|
|
282
|
-
return {"success": False, "status": 401,
|
|
283
|
-
"error": "密钥无效(401)。",
|
|
284
|
-
"hint": "检查条目「%s」的 api_key 是不是**密钥本身**(有些平台显示的是密钥名)。" % name}
|
|
285
|
-
if r.status_code == 404:
|
|
286
|
-
return {"success": False, "status": 404,
|
|
287
|
-
"error": "模型或地址不对(404)。",
|
|
288
|
-
"hint": "模型「%s」可能不存在或已下架;base_url 要填到 API 根(如火山是 /api/v3)。" % model}
|
|
289
|
-
if r.status_code == 429:
|
|
290
|
-
return {"success": False, "status": 429,
|
|
291
|
-
"error": "生图服务拒绝了调用(429,多半是额度/限流)。",
|
|
292
|
-
"hint": "火山方舟常见原因:「安心体验」把服务暂停了(免费额度为 0)—— 去控制台关掉它,或换一个有额度的模型。"}
|
|
293
|
-
if r.status_code >= 400:
|
|
294
|
-
try:
|
|
295
|
-
detail = r.json()
|
|
296
|
-
except ValueError:
|
|
297
|
-
detail = (r.text or "")[:300]
|
|
298
|
-
return {"success": False, "status": r.status_code,
|
|
299
|
-
"error": "生图服务返回 %d:%s" % (r.status_code, str(detail)[:300])}
|
|
300
|
-
|
|
301
|
-
try:
|
|
302
|
-
payload = r.json()
|
|
303
|
-
except ValueError:
|
|
304
|
-
return {"success": False, "error": "生图服务回的不是 JSON(可能被网关改写了)。"}
|
|
305
|
-
|
|
306
|
-
items = payload.get("data") if isinstance(payload, dict) else None
|
|
307
|
-
if not isinstance(items, list) or not items:
|
|
308
|
-
return {"success": False, "error": "生图服务没回图片(响应里没有 data[])。"}
|
|
309
|
-
|
|
310
|
-
#: 一次只处理第一张 —— 各家对一次多图的支持不一致(见模块 docstring)。
|
|
311
|
-
item = items[0] if isinstance(items[0], dict) else {}
|
|
312
|
-
out_dir = _out_dir()
|
|
313
|
-
dest = out_dir / ("media-gen-%s%s" % (_stamp(), ".png"))
|
|
314
|
-
|
|
315
|
-
b64 = item.get("b64_json")
|
|
316
|
-
if isinstance(b64, str) and b64:
|
|
317
|
-
return _write_b64(b64, model, name)
|
|
318
|
-
else:
|
|
319
|
-
url = str(item.get("url") or "").strip()
|
|
320
|
-
if not url:
|
|
321
|
-
return {"success": False, "error": "生图服务既没回 URL 也没回 base64。"}
|
|
322
|
-
ext = ".png"
|
|
323
|
-
low = urlsplit(url).path.lower()
|
|
324
|
-
for e in (".png", ".jpg", ".jpeg", ".webp", ".gif"):
|
|
325
|
-
if low.endswith(e):
|
|
326
|
-
ext = ".jpg" if e == ".jpeg" else e
|
|
327
|
-
break
|
|
328
|
-
dest = dest.with_suffix(ext)
|
|
329
|
-
err = _download_image(url, dest)
|
|
330
|
-
if err:
|
|
331
|
-
return {"success": False, "error": err}
|
|
332
|
-
|
|
333
|
-
return {
|
|
334
|
-
"success": True,
|
|
335
|
-
"entry": name,
|
|
336
|
-
"model": model,
|
|
337
|
-
"path": str(dest),
|
|
338
|
-
# 交给 `core/artifacts` 的契约(`collect_tool_artifacts`):路径 + 展示名。
|
|
339
|
-
"artifacts": [{"path": str(dest), "name": dest.name}],
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
# 本地后端—— Stable Diffusion WebUI / Forge
|
|
344
|
-
#
|
|
345
|
-
# 协议与厂商那条完全不同:`POST {base}/sdapi/v1/txt2img`,回的是
|
|
346
|
-
# base64 列表(`{"images": ["<b64 或 data URL>", …]}`)。
|
|
347
|
-
#
|
|
348
|
-
# 它不过出网闸:按定义它就是本机 —— 但"本机"只能是回环地址。
|
|
349
|
-
# 一个配置能指向 `192.168.x.x` 的话,这不是"本地接入",是内网请求
|
|
350
|
-
# (而 `check_url_egress` 那一层正是设计来挡这个的,不能因为改了名字就绕开)。
|
|
351
|
-
# 没有可验的现场:只做到"结构对 + 报错清楚"+ 机械读者(假响应)。
|
|
352
|
-
|
|
353
|
-
_LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
def _parse_size(size: str, default: int = 1024) -> tuple[int, int]:
|
|
357
|
-
"""`"1024x768"` / `"2K"` → `(w, h)`;读不出,默认方形。"""
|
|
358
|
-
s = str(size or "").strip().lower()
|
|
359
|
-
if "x" in s:
|
|
360
|
-
a, _, b = s.partition("x")
|
|
361
|
-
try:
|
|
362
|
-
w, h = int(a), int(b)
|
|
363
|
-
if 64 <= w <= 4096 and 64 <= h <= 4096:
|
|
364
|
-
return w, h
|
|
365
|
-
except ValueError:
|
|
366
|
-
pass
|
|
367
|
-
if s in ("1k", "2k", "4k"):
|
|
368
|
-
n = {"1k": 1024, "2k": 2048, "4k": 4096}[s]
|
|
369
|
-
return n, n
|
|
370
|
-
return default, default
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
def _write_b64(b64: str, model: str, entry: str) -> dict:
|
|
374
|
-
"""一段 base64(可带 `data:` 前缀)→ 工作区文件 + 记录。"""
|
|
375
|
-
s = str(b64 or "").strip()
|
|
376
|
-
if s.startswith("data:"):
|
|
377
|
-
s = s.partition(",")[2]
|
|
378
|
-
try:
|
|
379
|
-
raw = base64.b64decode(s, validate=False)
|
|
380
|
-
except Exception: # noqa: BLE001
|
|
381
|
-
return {"success": False, "error": "返回的 base64 解不开。"}
|
|
382
|
-
if not raw:
|
|
383
|
-
return {"success": False, "error": "返回的图片是空的。"}
|
|
384
|
-
dest = _out_dir() / ("media-gen-%s%s" % (_stamp(), _ext_for(raw)))
|
|
385
|
-
try:
|
|
386
|
-
dest.write_bytes(raw)
|
|
387
|
-
except OSError as exc: # noqa: BLE001
|
|
388
|
-
return {"success": False, "error": "写文件失败:%s" % exc}
|
|
389
|
-
return {"success": True, "entry": entry, "model": model, "path": str(dest),
|
|
390
|
-
"artifacts": [{"path": str(dest), "name": dest.name}]}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
def _generate_local(name: str, cfg: dict, prompt: str, size: str) -> dict:
|
|
394
|
-
base = str(cfg.get("base_url") or "http://127.0.0.1:7860").strip()
|
|
395
|
-
url = base.rstrip("/") + "/sdapi/v1/txt2img"
|
|
396
|
-
try:
|
|
397
|
-
host = (urlsplit(url).hostname or "").lower()
|
|
398
|
-
except ValueError:
|
|
399
|
-
host = ""
|
|
400
|
-
if host not in _LOOPBACK_HOSTS:
|
|
401
|
-
return {"success": False,
|
|
402
|
-
"error": "本地生图只允许本机地址(127.0.0.1 / localhost),收到「%s」。"
|
|
403
|
-
% (host or "(空)"),
|
|
404
|
-
"hint": "SD WebUI 默认 http://127.0.0.1:7860;"
|
|
405
|
-
"如果它跑在另一台机器上,用「厂商直连」那条。"}
|
|
406
|
-
w, h = _parse_size(size)
|
|
407
|
-
body = {"prompt": prompt, "width": w, "height": h, "steps": 20}
|
|
408
|
-
try:
|
|
409
|
-
with _client() as c:
|
|
410
|
-
r = c.post(url, json=body)
|
|
411
|
-
except Exception as exc: # noqa: BLE001
|
|
412
|
-
return {"success": False,
|
|
413
|
-
"error": "连不上本地 SD WebUI(%s)。" % type(exc).__name__,
|
|
414
|
-
"hint": "先启动它,并带 --api(默认地址 http://127.0.0.1:7860)。"}
|
|
415
|
-
if r.status_code >= 400:
|
|
416
|
-
try:
|
|
417
|
-
detail = str(r.json())[:200]
|
|
418
|
-
except ValueError:
|
|
419
|
-
detail = (r.text or "")[:200]
|
|
420
|
-
return {"success": False, "status": r.status_code,
|
|
421
|
-
"error": "SD WebUI 返回 %d:%s" % (r.status_code, detail)}
|
|
422
|
-
try:
|
|
423
|
-
payload = r.json()
|
|
424
|
-
except ValueError:
|
|
425
|
-
return {"success": False, "error": "SD WebUI 回的不是 JSON。"}
|
|
426
|
-
imgs = payload.get("images") if isinstance(payload, dict) else None
|
|
427
|
-
if not isinstance(imgs, list) or not imgs:
|
|
428
|
-
return {"success": False,
|
|
429
|
-
"error": "SD WebUI 没回图片(响应里没有 images[])。"}
|
|
430
|
-
return _write_b64(imgs[0], str(cfg.get("model") or "SD WebUI"), name)
|
|
1
|
+
"""生图 skill —— 厂商直连(OpenAI 兼容 `/images/generations`)。
|
|
2
|
+
|
|
3
|
+
## 为什么是原生 skill
|
|
4
|
+
|
|
5
|
+
对话模型自己不会画图。这一层把"让另一个服务画"变成一个工具调用:
|
|
6
|
+
描述进去、图出来,而且直接进聊天区(走 `core/artifacts` 那条呈现链,
|
|
7
|
+
不是给用户一段 URL 让他自己点)。
|
|
8
|
+
|
|
9
|
+
## 配置(`data/media_gen_credentials.json`)
|
|
10
|
+
|
|
11
|
+
独立文件,不进 `settings.json`(后者会被设置导入导出带走)::
|
|
12
|
+
|
|
13
|
+
{
|
|
14
|
+
"default": "ark",
|
|
15
|
+
"entries": {
|
|
16
|
+
"ark": {
|
|
17
|
+
"base_url": "https://ark.cn-beijing.volces.com/api/v3",
|
|
18
|
+
"model": "doubao-seedream-4-0-20260415",
|
|
19
|
+
"api_key": "…"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
- `base_url` 填到那家的 API 根(不一定是 `/v1`:火山是 `/api/v3`);
|
|
25
|
+
- 没配,工具照常注册,调用时回一句"还没配置"(不是崩、也不是假装成功);
|
|
26
|
+
- 密钥一个字都不回显(回执里只出现条目名与模型名)。
|
|
27
|
+
|
|
28
|
+
## 出网
|
|
29
|
+
|
|
30
|
+
两段,都过 `core/security.check_url_egress`(地板):
|
|
31
|
+
|
|
32
|
+
1. 请求厂商 API —— 地址由用户配置给出,必须过闸;
|
|
33
|
+
2. 下载返回的图片 URL —— 每一跳都过闸,且只同站跟随(跨站交回模型,
|
|
34
|
+
与 `§3.10` 同一套判据)。厂商给的 URL 有时效,拿到就下,不存着。
|
|
35
|
+
|
|
36
|
+
## 拿不到的东西
|
|
37
|
+
|
|
38
|
+
- 花费:直连厂商的响应里没有 cost 字段,不做收费通知;
|
|
39
|
+
- 多张:一次一张(各家的 `n` / `sequential_image_generation` 支持不一,
|
|
40
|
+
一套参数打所有模型会撞 400 —— 这是真调时踩过的坑)。
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import base64
|
|
46
|
+
import json
|
|
47
|
+
import time
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
from urllib.parse import urlsplit
|
|
50
|
+
|
|
51
|
+
__all__ = ["generate_image"]
|
|
52
|
+
|
|
53
|
+
_TIMEOUT_S = 120.0
|
|
54
|
+
_MAX_HOPS = 3
|
|
55
|
+
|
|
56
|
+
#: 图片字节 → 扩展名(按魔数,不信上游说的 mime)。
|
|
57
|
+
_EXT_BY_MIME = {
|
|
58
|
+
"image/png": ".png",
|
|
59
|
+
"image/jpeg": ".jpg",
|
|
60
|
+
"image/webp": ".webp",
|
|
61
|
+
"image/gif": ".gif",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def init(security_guard=None) -> None:
|
|
66
|
+
"""装载钩子。不读配置、不发请求 —— 那是每次调用时的事。"""
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# 配置
|
|
71
|
+
|
|
72
|
+
def _cred_path() -> Path:
|
|
73
|
+
"""配置文件在哪 —— 以 manifest 的 `settings.storage` 为准。
|
|
74
|
+
|
|
75
|
+
配置文件只有一处口径:界面(`/api/skills/<name>/config`)与本 handler
|
|
76
|
+
读写的必须是同一个文件,否则"界面上改了、模型那边没变"。
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
from core import skill_settings as _ss
|
|
80
|
+
p = _ss.storage_for("media_gen")
|
|
81
|
+
if p is not None:
|
|
82
|
+
return p
|
|
83
|
+
except Exception: # noqa: BLE001
|
|
84
|
+
pass
|
|
85
|
+
return Path("data") / "media_gen_credentials.json"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _load_entries() -> tuple[dict, str]:
|
|
89
|
+
"""`(entries, default)`;读不到/坏文件,空表(调用方给一句实话)。"""
|
|
90
|
+
p = _cred_path()
|
|
91
|
+
if not p.is_file():
|
|
92
|
+
return {}, ""
|
|
93
|
+
try:
|
|
94
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
95
|
+
except Exception as exc: # noqa: BLE001
|
|
96
|
+
print("[media_gen] %s 读不出来:%s: %s" % (p, type(exc).__name__, exc))
|
|
97
|
+
return {}, ""
|
|
98
|
+
if not isinstance(data, dict):
|
|
99
|
+
return {}, ""
|
|
100
|
+
entries = data.get("entries")
|
|
101
|
+
if not isinstance(entries, dict):
|
|
102
|
+
return {}, ""
|
|
103
|
+
clean = {str(k): v for k, v in entries.items() if isinstance(v, dict)}
|
|
104
|
+
return clean, str(data.get("default") or "")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _pick_entry(entries: dict, default: str, wanted: str) -> tuple[str, dict] | tuple[str, None]:
|
|
108
|
+
if not entries:
|
|
109
|
+
return "", None
|
|
110
|
+
name = str(wanted or "").strip() or default
|
|
111
|
+
if name and name in entries:
|
|
112
|
+
return name, entries[name]
|
|
113
|
+
if len(entries) == 1:
|
|
114
|
+
only = next(iter(entries))
|
|
115
|
+
return only, entries[only]
|
|
116
|
+
return "", None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _no_config() -> dict:
|
|
120
|
+
return {
|
|
121
|
+
"success": False,
|
|
122
|
+
"error": "还没有配置生图。",
|
|
123
|
+
"hint": ("在 %s 里写一条(base_url / model / api_key),"
|
|
124
|
+
"或者等设置页的「生图与视频」卡片建一条。" % _cred_path()),
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# HTTP
|
|
129
|
+
|
|
130
|
+
def _client(*, follow_redirects: bool = False):
|
|
131
|
+
"""按当前设置造一个 httpx 客户端(代理跟着设置页那一档走)。"""
|
|
132
|
+
from core import net_proxy as _np
|
|
133
|
+
import httpx
|
|
134
|
+
return _np.httpx_client(httpx.Client, follow_redirects=follow_redirects,
|
|
135
|
+
timeout=_TIMEOUT_S)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _api_url(base_url: str) -> str:
|
|
139
|
+
base = str(base_url or "").strip().rstrip("/")
|
|
140
|
+
return base + "/images/generations"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _same_site(a: str, b: str) -> bool:
|
|
144
|
+
"""同站:scheme + 端口 + 主机(忽略 `www.` 前缀,不吸子域)。"""
|
|
145
|
+
try:
|
|
146
|
+
pa, pb = urlsplit(a), urlsplit(b)
|
|
147
|
+
except ValueError:
|
|
148
|
+
return False
|
|
149
|
+
def norm(p):
|
|
150
|
+
host = (p.hostname or "").lower()
|
|
151
|
+
if host.startswith("www."):
|
|
152
|
+
host = host[4:]
|
|
153
|
+
port = p.port or (443 if (p.scheme or "").lower() == "https" else 80)
|
|
154
|
+
return (p.scheme or "").lower(), port, host
|
|
155
|
+
return norm(pa) == norm(pb)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _download_image(url: str, dest: Path) -> str:
|
|
159
|
+
"""把厂商给的 URL 立刻下到文件。返回错误串;成功,空串。
|
|
160
|
+
|
|
161
|
+
每一跳都过 `check_url_egress`(地板),只同站跟随 ——
|
|
162
|
+
跨站跳转不跟,交回模型/用户重来(与 `§3.10` 逐字同一条判据)。
|
|
163
|
+
"""
|
|
164
|
+
from core.security import UrlEgressError, check_url_egress
|
|
165
|
+
|
|
166
|
+
cur = url
|
|
167
|
+
for _hop in range(_MAX_HOPS + 1):
|
|
168
|
+
try:
|
|
169
|
+
cur = check_url_egress(cur)
|
|
170
|
+
except UrlEgressError as exc:
|
|
171
|
+
return "图片地址没通过出网闸:%s" % exc
|
|
172
|
+
try:
|
|
173
|
+
with _client() as c:
|
|
174
|
+
with c.stream("GET", cur) as r:
|
|
175
|
+
if 300 <= r.status_code < 400:
|
|
176
|
+
nxt = r.headers.get("location") or ""
|
|
177
|
+
if not nxt or not _same_site(cur, nxt):
|
|
178
|
+
return ("图片地址跨站跳转了(未跟随)。"
|
|
179
|
+
"让模型重新生成一次,或把它下载到本机后再处理。")
|
|
180
|
+
cur = nxt
|
|
181
|
+
continue
|
|
182
|
+
if r.status_code >= 400:
|
|
183
|
+
return "下载图片失败:HTTP %d" % r.status_code
|
|
184
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
185
|
+
tmp = dest.with_suffix(dest.suffix + ".part")
|
|
186
|
+
with tmp.open("wb") as f:
|
|
187
|
+
for chunk in r.iter_bytes():
|
|
188
|
+
f.write(chunk)
|
|
189
|
+
tmp.replace(dest)
|
|
190
|
+
return ""
|
|
191
|
+
except Exception as exc: # noqa: BLE001
|
|
192
|
+
return "下载图片失败(%s)。如果是网络问题:设置页的「出网代理」要选对。" % type(exc).__name__
|
|
193
|
+
return "图片地址跳转次数过多(>%d)。" % _MAX_HOPS
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _ext_for(data: bytes) -> str:
|
|
197
|
+
"""按魔数给扩展名(上游说的 mime 不是证据)。"""
|
|
198
|
+
try:
|
|
199
|
+
from core import artifacts as _art
|
|
200
|
+
mime = _art.sniff(data) or ""
|
|
201
|
+
except Exception: # noqa: BLE001
|
|
202
|
+
mime = ""
|
|
203
|
+
return _EXT_BY_MIME.get(mime, ".png")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _out_dir() -> Path:
|
|
207
|
+
"""落点:只有一处口径(`core/workspace.primary_output_dir`)。"""
|
|
208
|
+
from core.workspace import primary_output_dir
|
|
209
|
+
d = Path(str(primary_output_dir()))
|
|
210
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
211
|
+
return d
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _stamp() -> str:
|
|
215
|
+
return time.strftime("%Y%m%d-%H%M%S")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# 工具
|
|
219
|
+
|
|
220
|
+
def generate_image(prompt: str, size: str = "", entry: str = "") -> dict:
|
|
221
|
+
"""生成一张图片并保存到工作区(产出的图会直接显示在聊天里)。"""
|
|
222
|
+
text = str(prompt or "").strip()
|
|
223
|
+
if not text:
|
|
224
|
+
return {"success": False, "error": "prompt 不能为空。"}
|
|
225
|
+
|
|
226
|
+
entries, default = _load_entries()
|
|
227
|
+
name, cfg = _pick_entry(entries, default, entry)
|
|
228
|
+
if cfg is None:
|
|
229
|
+
if not entries:
|
|
230
|
+
return _no_config()
|
|
231
|
+
return {"success": False,
|
|
232
|
+
"error": "没有叫「%s」的配置。" % (entry or default),
|
|
233
|
+
"hint": "可用的条目:%s" % "、".join(sorted(entries))}
|
|
234
|
+
|
|
235
|
+
base_url = str(cfg.get("base_url") or "").strip()
|
|
236
|
+
model = str(cfg.get("model") or "").strip()
|
|
237
|
+
api_key = str(cfg.get("api_key") or "").strip()
|
|
238
|
+
kind = str(cfg.get("type") or "vendor").strip().lower()
|
|
239
|
+
|
|
240
|
+
# 本地后端:协议完全不同(SD WebUI 的 `/sdapi/v1/txt2img`),
|
|
241
|
+
# 而且它不过出网闸 —— 因为它按定义就是本机;但"本机"只能是回环地址,
|
|
242
|
+
# 否则一个配置就能把局域网当成生图服务(那是 SSRF,不是本地接入)。
|
|
243
|
+
if kind == "local":
|
|
244
|
+
return _generate_local(name, cfg, text, size)
|
|
245
|
+
|
|
246
|
+
if not base_url or not model or not api_key:
|
|
247
|
+
missing = [k for k, v in (("base_url", base_url), ("model", model),
|
|
248
|
+
("api_key", api_key)) if not v]
|
|
249
|
+
return {"success": False,
|
|
250
|
+
"error": "配置「%s」缺字段:%s。" % (name, "、".join(missing)),
|
|
251
|
+
"hint": "补在 %s 里(或等设置页那张卡)。" % _cred_path()}
|
|
252
|
+
|
|
253
|
+
body = {"model": model, "prompt": text}
|
|
254
|
+
if str(size or "").strip():
|
|
255
|
+
body["size"] = str(size).strip()
|
|
256
|
+
# 官方示例里 `watermark: true` —— 我们必须显式写 false(不往用户图上盖水印)。
|
|
257
|
+
body["watermark"] = False
|
|
258
|
+
body["response_format"] = "url"
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
from core.security import UrlEgressError, check_url_egress
|
|
262
|
+
except Exception as exc: # noqa: BLE001
|
|
263
|
+
return {"success": False, "error": "出网闸不可用(%s)。" % type(exc).__name__}
|
|
264
|
+
try:
|
|
265
|
+
api_url = check_url_egress(_api_url(base_url))
|
|
266
|
+
except UrlEgressError as exc:
|
|
267
|
+
return {"success": False, "error": "生图服务地址没通过出网闸:%s" % exc}
|
|
268
|
+
except Exception as exc: # noqa: BLE001
|
|
269
|
+
return {"success": False, "error": "生图服务地址不合法:%s" % exc}
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
with _client() as c:
|
|
273
|
+
r = c.post(api_url, headers={"Authorization": "Bearer " + api_key,
|
|
274
|
+
"Content-Type": "application/json"},
|
|
275
|
+
json=body)
|
|
276
|
+
except Exception as exc: # noqa: BLE001
|
|
277
|
+
return {"success": False,
|
|
278
|
+
"error": "连不上生图服务(%s)。" % type(exc).__name__,
|
|
279
|
+
"hint": "如果是网络问题:设置页的「出网代理」要选对(system / manual)。"}
|
|
280
|
+
|
|
281
|
+
if r.status_code == 401:
|
|
282
|
+
return {"success": False, "status": 401,
|
|
283
|
+
"error": "密钥无效(401)。",
|
|
284
|
+
"hint": "检查条目「%s」的 api_key 是不是**密钥本身**(有些平台显示的是密钥名)。" % name}
|
|
285
|
+
if r.status_code == 404:
|
|
286
|
+
return {"success": False, "status": 404,
|
|
287
|
+
"error": "模型或地址不对(404)。",
|
|
288
|
+
"hint": "模型「%s」可能不存在或已下架;base_url 要填到 API 根(如火山是 /api/v3)。" % model}
|
|
289
|
+
if r.status_code == 429:
|
|
290
|
+
return {"success": False, "status": 429,
|
|
291
|
+
"error": "生图服务拒绝了调用(429,多半是额度/限流)。",
|
|
292
|
+
"hint": "火山方舟常见原因:「安心体验」把服务暂停了(免费额度为 0)—— 去控制台关掉它,或换一个有额度的模型。"}
|
|
293
|
+
if r.status_code >= 400:
|
|
294
|
+
try:
|
|
295
|
+
detail = r.json()
|
|
296
|
+
except ValueError:
|
|
297
|
+
detail = (r.text or "")[:300]
|
|
298
|
+
return {"success": False, "status": r.status_code,
|
|
299
|
+
"error": "生图服务返回 %d:%s" % (r.status_code, str(detail)[:300])}
|
|
300
|
+
|
|
301
|
+
try:
|
|
302
|
+
payload = r.json()
|
|
303
|
+
except ValueError:
|
|
304
|
+
return {"success": False, "error": "生图服务回的不是 JSON(可能被网关改写了)。"}
|
|
305
|
+
|
|
306
|
+
items = payload.get("data") if isinstance(payload, dict) else None
|
|
307
|
+
if not isinstance(items, list) or not items:
|
|
308
|
+
return {"success": False, "error": "生图服务没回图片(响应里没有 data[])。"}
|
|
309
|
+
|
|
310
|
+
#: 一次只处理第一张 —— 各家对一次多图的支持不一致(见模块 docstring)。
|
|
311
|
+
item = items[0] if isinstance(items[0], dict) else {}
|
|
312
|
+
out_dir = _out_dir()
|
|
313
|
+
dest = out_dir / ("media-gen-%s%s" % (_stamp(), ".png"))
|
|
314
|
+
|
|
315
|
+
b64 = item.get("b64_json")
|
|
316
|
+
if isinstance(b64, str) and b64:
|
|
317
|
+
return _write_b64(b64, model, name)
|
|
318
|
+
else:
|
|
319
|
+
url = str(item.get("url") or "").strip()
|
|
320
|
+
if not url:
|
|
321
|
+
return {"success": False, "error": "生图服务既没回 URL 也没回 base64。"}
|
|
322
|
+
ext = ".png"
|
|
323
|
+
low = urlsplit(url).path.lower()
|
|
324
|
+
for e in (".png", ".jpg", ".jpeg", ".webp", ".gif"):
|
|
325
|
+
if low.endswith(e):
|
|
326
|
+
ext = ".jpg" if e == ".jpeg" else e
|
|
327
|
+
break
|
|
328
|
+
dest = dest.with_suffix(ext)
|
|
329
|
+
err = _download_image(url, dest)
|
|
330
|
+
if err:
|
|
331
|
+
return {"success": False, "error": err}
|
|
332
|
+
|
|
333
|
+
return {
|
|
334
|
+
"success": True,
|
|
335
|
+
"entry": name,
|
|
336
|
+
"model": model,
|
|
337
|
+
"path": str(dest),
|
|
338
|
+
# 交给 `core/artifacts` 的契约(`collect_tool_artifacts`):路径 + 展示名。
|
|
339
|
+
"artifacts": [{"path": str(dest), "name": dest.name}],
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# 本地后端—— Stable Diffusion WebUI / Forge
|
|
344
|
+
#
|
|
345
|
+
# 协议与厂商那条完全不同:`POST {base}/sdapi/v1/txt2img`,回的是
|
|
346
|
+
# base64 列表(`{"images": ["<b64 或 data URL>", …]}`)。
|
|
347
|
+
#
|
|
348
|
+
# 它不过出网闸:按定义它就是本机 —— 但"本机"只能是回环地址。
|
|
349
|
+
# 一个配置能指向 `192.168.x.x` 的话,这不是"本地接入",是内网请求
|
|
350
|
+
# (而 `check_url_egress` 那一层正是设计来挡这个的,不能因为改了名字就绕开)。
|
|
351
|
+
# 没有可验的现场:只做到"结构对 + 报错清楚"+ 机械读者(假响应)。
|
|
352
|
+
|
|
353
|
+
_LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _parse_size(size: str, default: int = 1024) -> tuple[int, int]:
|
|
357
|
+
"""`"1024x768"` / `"2K"` → `(w, h)`;读不出,默认方形。"""
|
|
358
|
+
s = str(size or "").strip().lower()
|
|
359
|
+
if "x" in s:
|
|
360
|
+
a, _, b = s.partition("x")
|
|
361
|
+
try:
|
|
362
|
+
w, h = int(a), int(b)
|
|
363
|
+
if 64 <= w <= 4096 and 64 <= h <= 4096:
|
|
364
|
+
return w, h
|
|
365
|
+
except ValueError:
|
|
366
|
+
pass
|
|
367
|
+
if s in ("1k", "2k", "4k"):
|
|
368
|
+
n = {"1k": 1024, "2k": 2048, "4k": 4096}[s]
|
|
369
|
+
return n, n
|
|
370
|
+
return default, default
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _write_b64(b64: str, model: str, entry: str) -> dict:
|
|
374
|
+
"""一段 base64(可带 `data:` 前缀)→ 工作区文件 + 记录。"""
|
|
375
|
+
s = str(b64 or "").strip()
|
|
376
|
+
if s.startswith("data:"):
|
|
377
|
+
s = s.partition(",")[2]
|
|
378
|
+
try:
|
|
379
|
+
raw = base64.b64decode(s, validate=False)
|
|
380
|
+
except Exception: # noqa: BLE001
|
|
381
|
+
return {"success": False, "error": "返回的 base64 解不开。"}
|
|
382
|
+
if not raw:
|
|
383
|
+
return {"success": False, "error": "返回的图片是空的。"}
|
|
384
|
+
dest = _out_dir() / ("media-gen-%s%s" % (_stamp(), _ext_for(raw)))
|
|
385
|
+
try:
|
|
386
|
+
dest.write_bytes(raw)
|
|
387
|
+
except OSError as exc: # noqa: BLE001
|
|
388
|
+
return {"success": False, "error": "写文件失败:%s" % exc}
|
|
389
|
+
return {"success": True, "entry": entry, "model": model, "path": str(dest),
|
|
390
|
+
"artifacts": [{"path": str(dest), "name": dest.name}]}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _generate_local(name: str, cfg: dict, prompt: str, size: str) -> dict:
|
|
394
|
+
base = str(cfg.get("base_url") or "http://127.0.0.1:7860").strip()
|
|
395
|
+
url = base.rstrip("/") + "/sdapi/v1/txt2img"
|
|
396
|
+
try:
|
|
397
|
+
host = (urlsplit(url).hostname or "").lower()
|
|
398
|
+
except ValueError:
|
|
399
|
+
host = ""
|
|
400
|
+
if host not in _LOOPBACK_HOSTS:
|
|
401
|
+
return {"success": False,
|
|
402
|
+
"error": "本地生图只允许本机地址(127.0.0.1 / localhost),收到「%s」。"
|
|
403
|
+
% (host or "(空)"),
|
|
404
|
+
"hint": "SD WebUI 默认 http://127.0.0.1:7860;"
|
|
405
|
+
"如果它跑在另一台机器上,用「厂商直连」那条。"}
|
|
406
|
+
w, h = _parse_size(size)
|
|
407
|
+
body = {"prompt": prompt, "width": w, "height": h, "steps": 20}
|
|
408
|
+
try:
|
|
409
|
+
with _client() as c:
|
|
410
|
+
r = c.post(url, json=body)
|
|
411
|
+
except Exception as exc: # noqa: BLE001
|
|
412
|
+
return {"success": False,
|
|
413
|
+
"error": "连不上本地 SD WebUI(%s)。" % type(exc).__name__,
|
|
414
|
+
"hint": "先启动它,并带 --api(默认地址 http://127.0.0.1:7860)。"}
|
|
415
|
+
if r.status_code >= 400:
|
|
416
|
+
try:
|
|
417
|
+
detail = str(r.json())[:200]
|
|
418
|
+
except ValueError:
|
|
419
|
+
detail = (r.text or "")[:200]
|
|
420
|
+
return {"success": False, "status": r.status_code,
|
|
421
|
+
"error": "SD WebUI 返回 %d:%s" % (r.status_code, detail)}
|
|
422
|
+
try:
|
|
423
|
+
payload = r.json()
|
|
424
|
+
except ValueError:
|
|
425
|
+
return {"success": False, "error": "SD WebUI 回的不是 JSON。"}
|
|
426
|
+
imgs = payload.get("images") if isinstance(payload, dict) else None
|
|
427
|
+
if not isinstance(imgs, list) or not imgs:
|
|
428
|
+
return {"success": False,
|
|
429
|
+
"error": "SD WebUI 没回图片(响应里没有 images[])。"}
|
|
430
|
+
return _write_b64(imgs[0], str(cfg.get("model") or "SD WebUI"), name)
|