dsh-plugin-image-workbench 1.1.5 → 1.1.7

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.
Files changed (173) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +5 -3
  3. package/README.md +7 -3
  4. package/client.js +241 -241
  5. package/cordis.patch.yml +14 -14
  6. package/host.js +51 -0
  7. package/install.mjs +333 -387
  8. package/package.json +3 -2
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -154
  11. package/server/access.py +26 -26
  12. package/server/app.py +1371 -1329
  13. package/server/catalog.py +147 -147
  14. package/server/composer.py +391 -391
  15. package/server/drafts.py +158 -158
  16. package/server/history.py +575 -575
  17. package/server/imaging.py +172 -172
  18. package/server/pool.py +1335 -1335
  19. package/server/pool_admin.py +921 -921
  20. package/server/pool_service.py +1073 -1073
  21. package/server/requirements.txt +6 -6
  22. package/server/smoke_check.py +402 -402
  23. package/server/static/access.html +202 -202
  24. package/server/static/index.html +15 -0
  25. package/vendor/chatgpt2api/source/.env.example +82 -82
  26. package/vendor/chatgpt2api/source/.python-version +1 -1
  27. package/vendor/chatgpt2api/source/LICENSE +21 -21
  28. package/vendor/chatgpt2api/source/README.md +391 -391
  29. package/vendor/chatgpt2api/source/VERSION +1 -1
  30. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  31. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  32. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  33. package/vendor/chatgpt2api/source/api/app.py +62 -62
  34. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  35. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  36. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  37. package/vendor/chatgpt2api/source/api/support.py +134 -134
  38. package/vendor/chatgpt2api/source/api/system.py +365 -365
  39. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  40. package/vendor/chatgpt2api/source/config.default.json +108 -108
  41. package/vendor/chatgpt2api/source/main.py +9 -9
  42. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  43. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  44. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  45. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  46. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  47. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  48. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  49. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  50. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  51. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  52. package/vendor/chatgpt2api/source/services/config.py +667 -667
  53. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  54. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  55. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  56. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  57. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  58. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  59. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  60. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  61. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  62. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  63. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  64. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  65. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  66. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  67. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  68. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  69. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  70. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  75. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  76. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  77. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  78. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  79. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  80. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  81. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  82. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  83. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  84. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  85. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  86. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  87. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  88. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  89. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  90. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  91. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  92. package/vendor/chatgpt2api/source/uv.lock +904 -904
  93. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  94. package/vendor/chatgpt2api/source/web/components.json +24 -24
  95. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  96. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  97. package/vendor/chatgpt2api/source/web/package.json +58 -58
  98. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  100. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  107. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  108. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  109. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  112. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  113. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  114. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  115. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  116. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  117. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  118. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  133. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  134. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  135. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  136. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  137. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  138. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  139. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  140. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  141. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  142. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  143. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  144. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  145. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  146. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  147. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  149. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  150. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  151. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  152. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  153. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  154. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  155. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  156. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  157. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  158. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  159. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  160. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  161. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  162. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  163. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  164. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  165. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  166. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  167. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  168. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  169. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  170. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  171. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  172. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  173. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,309 +1,309 @@
1
- from __future__ import annotations
2
-
3
- import base64
4
- import binascii
5
- import json
6
- import mimetypes
7
- import re
8
- from pathlib import PurePosixPath
9
- from typing import Any, TypeGuard
10
- from urllib.parse import unquote, unquote_to_bytes, urlparse
11
-
12
- from curl_cffi import requests
13
- from fastapi import HTTPException, Request
14
- from fastapi.concurrency import run_in_threadpool
15
- from starlette.datastructures import UploadFile
16
-
17
- from services.proxy_service import proxy_settings
18
-
19
- ImageInput = tuple[bytes, str, str]
20
- ImageSource = str | UploadFile | ImageInput
21
-
22
- MAX_IMAGE_REFERENCE_BYTES = 50 * 1024 * 1024
23
- IMAGE_REFERENCE_FIELDS = {"image", "image[]", "images", "images[]", "image_url", "image_url[]"}
24
- MASK_REFERENCE_FIELDS = {"mask", "mask[]"}
25
-
26
-
27
- def _clean(value: object, default: str = "") -> str:
28
- """清理字符串:转换为字符串并去掉首尾空白。"""
29
- text = str(value if value is not None else default).strip()
30
- return text or default
31
-
32
-
33
- def _is_upload(value: object) -> TypeGuard[UploadFile]:
34
- """识别上传文件:兼容 Starlette 表单返回的 UploadFile。"""
35
- return isinstance(value, UploadFile)
36
-
37
-
38
- def _parse_bool(value: object) -> bool | None:
39
- """解析布尔字段:兼容 JSON 布尔值和表单字符串。"""
40
- if value is None or value == "":
41
- return None
42
- if isinstance(value, bool):
43
- return value
44
- text = _clean(value).lower()
45
- if text in {"true", "1", "yes", "y", "on"}:
46
- return True
47
- if text in {"false", "0", "no", "n", "off"}:
48
- return False
49
- raise HTTPException(status_code=400, detail={"error": "stream must be a boolean"})
50
-
51
-
52
- def _parse_count(value: object) -> int:
53
- """解析生成数量:保持图片接口的 1 到 4 限制。"""
54
- try:
55
- count = int(value or 1)
56
- except (TypeError, ValueError) as exc:
57
- raise HTTPException(status_code=400, detail={"error": "n must be an integer"}) from exc
58
- if count < 1 or count > 4:
59
- raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
60
- return count
61
-
62
-
63
- def _payload_from_fields(fields: dict[str, Any]) -> dict[str, Any]:
64
- """构造图片编辑载荷:从表单或 JSON 字段提取通用参数。"""
65
- prompt = _clean(fields.get("prompt"))
66
- if not prompt:
67
- raise HTTPException(status_code=400, detail={"error": "prompt is required"})
68
- payload = {
69
- "prompt": prompt,
70
- "model": _clean(fields.get("model"), "gpt-image-2"),
71
- "n": _parse_count(fields.get("n")),
72
- "size": _clean(fields.get("size")) or None,
73
- "quality": _clean(fields.get("quality"), "auto"),
74
- "response_format": _clean(fields.get("response_format"), "b64_json"),
75
- "stream": _parse_bool(fields.get("stream")),
76
- }
77
- if "client_task_id" in fields:
78
- payload["client_task_id"] = _clean(fields.get("client_task_id"))
79
- return payload
80
-
81
-
82
- def _json_reference_value(value: object) -> object:
83
- """解析表单图片引用:支持把 images 字段写成 JSON 字符串。"""
84
- if not isinstance(value, str):
85
- return value
86
- text = value.strip()
87
- if not text or text[0] not in "[{":
88
- return value
89
- try:
90
- return json.loads(text)
91
- except json.JSONDecodeError:
92
- return value
93
-
94
-
95
- def _decode_base64_image(value: object, filename: str, mime_type: str) -> ImageInput:
96
- try:
97
- data = base64.b64decode(str(value).strip(), validate=True)
98
- except (binascii.Error, ValueError) as exc:
99
- raise HTTPException(status_code=400, detail={"error": "invalid base64 image data"}) from exc
100
- if not data:
101
- raise HTTPException(status_code=400, detail={"error": "image file is empty"})
102
- if len(data) > MAX_IMAGE_REFERENCE_BYTES:
103
- raise HTTPException(status_code=400, detail={"error": "image URL exceeds 50MB limit"})
104
- return data, filename, mime_type
105
-
106
-
107
- def _source_from_object(value: dict[str, Any]) -> list[ImageSource]:
108
- """提取图片引用对象:支持 image_url 或 url,明确拒绝 file_id。"""
109
- has_url = "image_url" in value or "url" in value
110
- if value.get("file_id"):
111
- raise HTTPException(
112
- status_code=400,
113
- detail={"error": "file_id image references are not supported; use image_url instead"},
114
- )
115
- inline = value.get("b64_json") or value.get("base64")
116
- if inline:
117
- filename = _clean(value.get("filename") or value.get("file_name"), "image.png")
118
- mime_type = _clean(value.get("mime_type") or value.get("mimeType"), "image/png")
119
- return [_decode_base64_image(inline, filename, mime_type)]
120
- if not has_url:
121
- raise HTTPException(status_code=400, detail={"error": "image reference must include image_url"})
122
- image_url = value.get("image_url", value.get("url"))
123
- if isinstance(image_url, dict):
124
- image_url = image_url.get("url")
125
- return _sources_from_value(image_url)
126
-
127
-
128
- def _sources_from_value(value: object) -> list[ImageSource]:
129
- """展开图片引用:把字符串、数组和对象统一成图片来源列表。"""
130
- value = _json_reference_value(value)
131
- if _is_upload(value):
132
- return [value]
133
- if isinstance(value, str):
134
- text = value.strip()
135
- if not text:
136
- return []
137
- if text.lower().startswith(("data:", "http://", "https://")):
138
- return [text]
139
- return [_decode_base64_image(text, "image.png", "image/png")]
140
- if isinstance(value, list):
141
- sources: list[ImageSource] = []
142
- for item in value:
143
- sources.extend(_sources_from_value(item))
144
- return sources
145
- if isinstance(value, dict):
146
- return _source_from_object(value)
147
- if value is None:
148
- return []
149
- raise HTTPException(status_code=400, detail={"error": "invalid image reference"})
150
-
151
-
152
- def _json_image_sources(body: dict[str, Any]) -> list[ImageSource]:
153
- """读取 JSON 图片引用:优先支持官方 images 数组字段。"""
154
- sources: list[ImageSource] = []
155
- for key in ("images", "image", "image_url"):
156
- if key in body:
157
- sources.extend(_sources_from_value(body.get(key)))
158
- return sources
159
-
160
-
161
- def _json_mask_sources(body: dict[str, Any]) -> list[ImageSource]:
162
- """读取 JSON mask 引用。"""
163
- mask = body.get("mask")
164
- if mask is not None:
165
- return _sources_from_value(mask)
166
- return []
167
-
168
-
169
- async def parse_image_edit_request(request: Request) -> tuple[dict[str, Any], list[ImageSource], list[ImageSource]]:
170
- """解析图片编辑请求:同时支持 multipart 上传和官方 JSON 图片 URL。
171
-
172
- 返回 (payload, image_sources, mask_sources)
173
- """
174
- content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
175
- if content_type == "application/json":
176
- try:
177
- body = await request.json()
178
- except json.JSONDecodeError as exc:
179
- raise HTTPException(status_code=400, detail={"error": "invalid JSON body"}) from exc
180
- if not isinstance(body, dict):
181
- raise HTTPException(status_code=400, detail={"error": "JSON body must be an object"})
182
- return _payload_from_fields(body), _json_image_sources(body), _json_mask_sources(body)
183
-
184
- form = await request.form()
185
- fields: dict[str, Any] = {}
186
- for key in ("client_task_id", "prompt", "model", "n", "size", "quality", "response_format", "stream"):
187
- value = form.get(key)
188
- if isinstance(value, str):
189
- fields[key] = value
190
- sources: list[ImageSource] = []
191
- mask_sources: list[ImageSource] = []
192
- for key, value in form.multi_items():
193
- if key in IMAGE_REFERENCE_FIELDS:
194
- sources.extend(_sources_from_value(value))
195
- elif key in MASK_REFERENCE_FIELDS:
196
- mask_sources.extend(_sources_from_value(value))
197
- return _payload_from_fields(fields), sources, mask_sources
198
-
199
-
200
- def _extension_from_mime(mime_type: str) -> str:
201
- """推导图片扩展名:把 MIME 类型转换为常见文件后缀。"""
202
- subtype = mime_type.split("/", 1)[1].split("+", 1)[0] if "/" in mime_type else "png"
203
- if subtype == "jpeg":
204
- return "jpg"
205
- return re.sub(r"[^a-z0-9]+", "", subtype.lower()) or "png"
206
-
207
-
208
- def _safe_filename(name: str, mime_type: str, fallback: str) -> str:
209
- """生成安全文件名:清理 URL 文件名并补齐扩展名。"""
210
- cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("._")
211
- if not cleaned:
212
- cleaned = fallback
213
- if "." not in cleaned:
214
- cleaned = f"{cleaned}.{_extension_from_mime(mime_type)}"
215
- return cleaned
216
-
217
-
218
- def _decode_data_url(url: str) -> ImageInput:
219
- """解码 data URL:把内联图片转成标准图片输入元组。"""
220
- header, separator, payload = url.partition(",")
221
- if not separator:
222
- raise HTTPException(status_code=400, detail={"error": "invalid data image URL"})
223
- mime_type = header.split(";", 1)[0].removeprefix("data:") or "image/png"
224
- if not mime_type.startswith("image/"):
225
- raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
226
- try:
227
- data = base64.b64decode(payload, validate=True) if ";base64" in header else unquote_to_bytes(payload)
228
- except (binascii.Error, ValueError) as exc:
229
- raise HTTPException(status_code=400, detail={"error": "invalid data image URL"}) from exc
230
- if not data:
231
- raise HTTPException(status_code=400, detail={"error": "image URL is empty"})
232
- if len(data) > MAX_IMAGE_REFERENCE_BYTES:
233
- raise HTTPException(status_code=400, detail={"error": "image URL exceeds 50MB limit"})
234
- return data, f"image_url.{_extension_from_mime(mime_type)}", mime_type
235
-
236
-
237
- def _response_mime_type(response: requests.Response, parsed_path: str) -> str:
238
- """识别下载图片类型:优先响应头,必要时按 URL 后缀推断。"""
239
- header_type = str(response.headers.get("content-type") or "").split(";", 1)[0].strip().lower()
240
- guessed_type = mimetypes.guess_type(parsed_path)[0] or ""
241
- if header_type.startswith("image/"):
242
- return header_type
243
- if header_type and header_type not in {"application/octet-stream", "binary/octet-stream"}:
244
- raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
245
- if guessed_type.startswith("image/"):
246
- return guessed_type
247
- if not header_type or header_type in {"application/octet-stream", "binary/octet-stream"}:
248
- return "image/png"
249
- raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
250
-
251
-
252
- def _filename_from_url(parsed_path: str, mime_type: str) -> str:
253
- """生成 URL 图片文件名:从链接路径提取名称并做安全化。"""
254
- raw_name = PurePosixPath(unquote(parsed_path)).name
255
- return _safe_filename(raw_name, mime_type, "image_url")
256
-
257
-
258
- def _download_image_url(url: str) -> ImageInput:
259
- """下载远程图片:把 http/https 图片链接转成标准图片输入元组。"""
260
- source = _clean(url)
261
- if source.startswith("data:"):
262
- return _decode_data_url(source)
263
- parsed = urlparse(source)
264
- if parsed.scheme not in {"http", "https"} or not parsed.netloc:
265
- raise HTTPException(status_code=400, detail={"error": "image_url must be an http or https URL"})
266
- try:
267
- response = requests.get(
268
- source,
269
- headers={"Accept": "image/*,*/*;q=0.8", "User-Agent": "chatgpt2api image fetcher"},
270
- timeout=60,
271
- allow_redirects=True,
272
- **proxy_settings.build_session_kwargs(),
273
- )
274
- except Exception as exc:
275
- raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: {exc}"}) from exc
276
- if not 200 <= response.status_code < 300:
277
- raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: HTTP {response.status_code}"})
278
- content_length = _clean(response.headers.get("content-length"))
279
- if content_length and content_length.isdigit() and int(content_length) > MAX_IMAGE_REFERENCE_BYTES:
280
- raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
281
- data = response.content
282
- if not data:
283
- raise HTTPException(status_code=400, detail={"error": "image_url returned empty content"})
284
- if len(data) > MAX_IMAGE_REFERENCE_BYTES:
285
- raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
286
- mime_type = _response_mime_type(response, parsed.path)
287
- return data, _filename_from_url(parsed.path, mime_type), mime_type
288
-
289
-
290
- async def read_image_sources(sources: list[ImageSource]) -> list[ImageInput]:
291
- """读取图片来源:上传文件直接读取,URL 下载后统一返回图片元组。"""
292
- images: list[ImageInput] = []
293
- for source in sources:
294
- if isinstance(source, tuple):
295
- images.append(source)
296
- continue
297
- if _is_upload(source):
298
- try:
299
- image_data = await source.read()
300
- finally:
301
- await source.close()
302
- if not image_data:
303
- raise HTTPException(status_code=400, detail={"error": "image file is empty"})
304
- images.append((image_data, source.filename or "image.png", source.content_type or "image/png"))
305
- continue
306
- images.append(await run_in_threadpool(_download_image_url, source))
307
- if not images:
308
- raise HTTPException(status_code=400, detail={"error": "image file or image_url is required"})
309
- return images
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import binascii
5
+ import json
6
+ import mimetypes
7
+ import re
8
+ from pathlib import PurePosixPath
9
+ from typing import Any, TypeGuard
10
+ from urllib.parse import unquote, unquote_to_bytes, urlparse
11
+
12
+ from curl_cffi import requests
13
+ from fastapi import HTTPException, Request
14
+ from fastapi.concurrency import run_in_threadpool
15
+ from starlette.datastructures import UploadFile
16
+
17
+ from services.proxy_service import proxy_settings
18
+
19
+ ImageInput = tuple[bytes, str, str]
20
+ ImageSource = str | UploadFile | ImageInput
21
+
22
+ MAX_IMAGE_REFERENCE_BYTES = 50 * 1024 * 1024
23
+ IMAGE_REFERENCE_FIELDS = {"image", "image[]", "images", "images[]", "image_url", "image_url[]"}
24
+ MASK_REFERENCE_FIELDS = {"mask", "mask[]"}
25
+
26
+
27
+ def _clean(value: object, default: str = "") -> str:
28
+ """清理字符串:转换为字符串并去掉首尾空白。"""
29
+ text = str(value if value is not None else default).strip()
30
+ return text or default
31
+
32
+
33
+ def _is_upload(value: object) -> TypeGuard[UploadFile]:
34
+ """识别上传文件:兼容 Starlette 表单返回的 UploadFile。"""
35
+ return isinstance(value, UploadFile)
36
+
37
+
38
+ def _parse_bool(value: object) -> bool | None:
39
+ """解析布尔字段:兼容 JSON 布尔值和表单字符串。"""
40
+ if value is None or value == "":
41
+ return None
42
+ if isinstance(value, bool):
43
+ return value
44
+ text = _clean(value).lower()
45
+ if text in {"true", "1", "yes", "y", "on"}:
46
+ return True
47
+ if text in {"false", "0", "no", "n", "off"}:
48
+ return False
49
+ raise HTTPException(status_code=400, detail={"error": "stream must be a boolean"})
50
+
51
+
52
+ def _parse_count(value: object) -> int:
53
+ """解析生成数量:保持图片接口的 1 到 4 限制。"""
54
+ try:
55
+ count = int(value or 1)
56
+ except (TypeError, ValueError) as exc:
57
+ raise HTTPException(status_code=400, detail={"error": "n must be an integer"}) from exc
58
+ if count < 1 or count > 4:
59
+ raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
60
+ return count
61
+
62
+
63
+ def _payload_from_fields(fields: dict[str, Any]) -> dict[str, Any]:
64
+ """构造图片编辑载荷:从表单或 JSON 字段提取通用参数。"""
65
+ prompt = _clean(fields.get("prompt"))
66
+ if not prompt:
67
+ raise HTTPException(status_code=400, detail={"error": "prompt is required"})
68
+ payload = {
69
+ "prompt": prompt,
70
+ "model": _clean(fields.get("model"), "gpt-image-2"),
71
+ "n": _parse_count(fields.get("n")),
72
+ "size": _clean(fields.get("size")) or None,
73
+ "quality": _clean(fields.get("quality"), "auto"),
74
+ "response_format": _clean(fields.get("response_format"), "b64_json"),
75
+ "stream": _parse_bool(fields.get("stream")),
76
+ }
77
+ if "client_task_id" in fields:
78
+ payload["client_task_id"] = _clean(fields.get("client_task_id"))
79
+ return payload
80
+
81
+
82
+ def _json_reference_value(value: object) -> object:
83
+ """解析表单图片引用:支持把 images 字段写成 JSON 字符串。"""
84
+ if not isinstance(value, str):
85
+ return value
86
+ text = value.strip()
87
+ if not text or text[0] not in "[{":
88
+ return value
89
+ try:
90
+ return json.loads(text)
91
+ except json.JSONDecodeError:
92
+ return value
93
+
94
+
95
+ def _decode_base64_image(value: object, filename: str, mime_type: str) -> ImageInput:
96
+ try:
97
+ data = base64.b64decode(str(value).strip(), validate=True)
98
+ except (binascii.Error, ValueError) as exc:
99
+ raise HTTPException(status_code=400, detail={"error": "invalid base64 image data"}) from exc
100
+ if not data:
101
+ raise HTTPException(status_code=400, detail={"error": "image file is empty"})
102
+ if len(data) > MAX_IMAGE_REFERENCE_BYTES:
103
+ raise HTTPException(status_code=400, detail={"error": "image URL exceeds 50MB limit"})
104
+ return data, filename, mime_type
105
+
106
+
107
+ def _source_from_object(value: dict[str, Any]) -> list[ImageSource]:
108
+ """提取图片引用对象:支持 image_url 或 url,明确拒绝 file_id。"""
109
+ has_url = "image_url" in value or "url" in value
110
+ if value.get("file_id"):
111
+ raise HTTPException(
112
+ status_code=400,
113
+ detail={"error": "file_id image references are not supported; use image_url instead"},
114
+ )
115
+ inline = value.get("b64_json") or value.get("base64")
116
+ if inline:
117
+ filename = _clean(value.get("filename") or value.get("file_name"), "image.png")
118
+ mime_type = _clean(value.get("mime_type") or value.get("mimeType"), "image/png")
119
+ return [_decode_base64_image(inline, filename, mime_type)]
120
+ if not has_url:
121
+ raise HTTPException(status_code=400, detail={"error": "image reference must include image_url"})
122
+ image_url = value.get("image_url", value.get("url"))
123
+ if isinstance(image_url, dict):
124
+ image_url = image_url.get("url")
125
+ return _sources_from_value(image_url)
126
+
127
+
128
+ def _sources_from_value(value: object) -> list[ImageSource]:
129
+ """展开图片引用:把字符串、数组和对象统一成图片来源列表。"""
130
+ value = _json_reference_value(value)
131
+ if _is_upload(value):
132
+ return [value]
133
+ if isinstance(value, str):
134
+ text = value.strip()
135
+ if not text:
136
+ return []
137
+ if text.lower().startswith(("data:", "http://", "https://")):
138
+ return [text]
139
+ return [_decode_base64_image(text, "image.png", "image/png")]
140
+ if isinstance(value, list):
141
+ sources: list[ImageSource] = []
142
+ for item in value:
143
+ sources.extend(_sources_from_value(item))
144
+ return sources
145
+ if isinstance(value, dict):
146
+ return _source_from_object(value)
147
+ if value is None:
148
+ return []
149
+ raise HTTPException(status_code=400, detail={"error": "invalid image reference"})
150
+
151
+
152
+ def _json_image_sources(body: dict[str, Any]) -> list[ImageSource]:
153
+ """读取 JSON 图片引用:优先支持官方 images 数组字段。"""
154
+ sources: list[ImageSource] = []
155
+ for key in ("images", "image", "image_url"):
156
+ if key in body:
157
+ sources.extend(_sources_from_value(body.get(key)))
158
+ return sources
159
+
160
+
161
+ def _json_mask_sources(body: dict[str, Any]) -> list[ImageSource]:
162
+ """读取 JSON mask 引用。"""
163
+ mask = body.get("mask")
164
+ if mask is not None:
165
+ return _sources_from_value(mask)
166
+ return []
167
+
168
+
169
+ async def parse_image_edit_request(request: Request) -> tuple[dict[str, Any], list[ImageSource], list[ImageSource]]:
170
+ """解析图片编辑请求:同时支持 multipart 上传和官方 JSON 图片 URL。
171
+
172
+ 返回 (payload, image_sources, mask_sources)
173
+ """
174
+ content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
175
+ if content_type == "application/json":
176
+ try:
177
+ body = await request.json()
178
+ except json.JSONDecodeError as exc:
179
+ raise HTTPException(status_code=400, detail={"error": "invalid JSON body"}) from exc
180
+ if not isinstance(body, dict):
181
+ raise HTTPException(status_code=400, detail={"error": "JSON body must be an object"})
182
+ return _payload_from_fields(body), _json_image_sources(body), _json_mask_sources(body)
183
+
184
+ form = await request.form()
185
+ fields: dict[str, Any] = {}
186
+ for key in ("client_task_id", "prompt", "model", "n", "size", "quality", "response_format", "stream"):
187
+ value = form.get(key)
188
+ if isinstance(value, str):
189
+ fields[key] = value
190
+ sources: list[ImageSource] = []
191
+ mask_sources: list[ImageSource] = []
192
+ for key, value in form.multi_items():
193
+ if key in IMAGE_REFERENCE_FIELDS:
194
+ sources.extend(_sources_from_value(value))
195
+ elif key in MASK_REFERENCE_FIELDS:
196
+ mask_sources.extend(_sources_from_value(value))
197
+ return _payload_from_fields(fields), sources, mask_sources
198
+
199
+
200
+ def _extension_from_mime(mime_type: str) -> str:
201
+ """推导图片扩展名:把 MIME 类型转换为常见文件后缀。"""
202
+ subtype = mime_type.split("/", 1)[1].split("+", 1)[0] if "/" in mime_type else "png"
203
+ if subtype == "jpeg":
204
+ return "jpg"
205
+ return re.sub(r"[^a-z0-9]+", "", subtype.lower()) or "png"
206
+
207
+
208
+ def _safe_filename(name: str, mime_type: str, fallback: str) -> str:
209
+ """生成安全文件名:清理 URL 文件名并补齐扩展名。"""
210
+ cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("._")
211
+ if not cleaned:
212
+ cleaned = fallback
213
+ if "." not in cleaned:
214
+ cleaned = f"{cleaned}.{_extension_from_mime(mime_type)}"
215
+ return cleaned
216
+
217
+
218
+ def _decode_data_url(url: str) -> ImageInput:
219
+ """解码 data URL:把内联图片转成标准图片输入元组。"""
220
+ header, separator, payload = url.partition(",")
221
+ if not separator:
222
+ raise HTTPException(status_code=400, detail={"error": "invalid data image URL"})
223
+ mime_type = header.split(";", 1)[0].removeprefix("data:") or "image/png"
224
+ if not mime_type.startswith("image/"):
225
+ raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
226
+ try:
227
+ data = base64.b64decode(payload, validate=True) if ";base64" in header else unquote_to_bytes(payload)
228
+ except (binascii.Error, ValueError) as exc:
229
+ raise HTTPException(status_code=400, detail={"error": "invalid data image URL"}) from exc
230
+ if not data:
231
+ raise HTTPException(status_code=400, detail={"error": "image URL is empty"})
232
+ if len(data) > MAX_IMAGE_REFERENCE_BYTES:
233
+ raise HTTPException(status_code=400, detail={"error": "image URL exceeds 50MB limit"})
234
+ return data, f"image_url.{_extension_from_mime(mime_type)}", mime_type
235
+
236
+
237
+ def _response_mime_type(response: requests.Response, parsed_path: str) -> str:
238
+ """识别下载图片类型:优先响应头,必要时按 URL 后缀推断。"""
239
+ header_type = str(response.headers.get("content-type") or "").split(";", 1)[0].strip().lower()
240
+ guessed_type = mimetypes.guess_type(parsed_path)[0] or ""
241
+ if header_type.startswith("image/"):
242
+ return header_type
243
+ if header_type and header_type not in {"application/octet-stream", "binary/octet-stream"}:
244
+ raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
245
+ if guessed_type.startswith("image/"):
246
+ return guessed_type
247
+ if not header_type or header_type in {"application/octet-stream", "binary/octet-stream"}:
248
+ return "image/png"
249
+ raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
250
+
251
+
252
+ def _filename_from_url(parsed_path: str, mime_type: str) -> str:
253
+ """生成 URL 图片文件名:从链接路径提取名称并做安全化。"""
254
+ raw_name = PurePosixPath(unquote(parsed_path)).name
255
+ return _safe_filename(raw_name, mime_type, "image_url")
256
+
257
+
258
+ def _download_image_url(url: str) -> ImageInput:
259
+ """下载远程图片:把 http/https 图片链接转成标准图片输入元组。"""
260
+ source = _clean(url)
261
+ if source.startswith("data:"):
262
+ return _decode_data_url(source)
263
+ parsed = urlparse(source)
264
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
265
+ raise HTTPException(status_code=400, detail={"error": "image_url must be an http or https URL"})
266
+ try:
267
+ response = requests.get(
268
+ source,
269
+ headers={"Accept": "image/*,*/*;q=0.8", "User-Agent": "chatgpt2api image fetcher"},
270
+ timeout=60,
271
+ allow_redirects=True,
272
+ **proxy_settings.build_session_kwargs(),
273
+ )
274
+ except Exception as exc:
275
+ raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: {exc}"}) from exc
276
+ if not 200 <= response.status_code < 300:
277
+ raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: HTTP {response.status_code}"})
278
+ content_length = _clean(response.headers.get("content-length"))
279
+ if content_length and content_length.isdigit() and int(content_length) > MAX_IMAGE_REFERENCE_BYTES:
280
+ raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
281
+ data = response.content
282
+ if not data:
283
+ raise HTTPException(status_code=400, detail={"error": "image_url returned empty content"})
284
+ if len(data) > MAX_IMAGE_REFERENCE_BYTES:
285
+ raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
286
+ mime_type = _response_mime_type(response, parsed.path)
287
+ return data, _filename_from_url(parsed.path, mime_type), mime_type
288
+
289
+
290
+ async def read_image_sources(sources: list[ImageSource]) -> list[ImageInput]:
291
+ """读取图片来源:上传文件直接读取,URL 下载后统一返回图片元组。"""
292
+ images: list[ImageInput] = []
293
+ for source in sources:
294
+ if isinstance(source, tuple):
295
+ images.append(source)
296
+ continue
297
+ if _is_upload(source):
298
+ try:
299
+ image_data = await source.read()
300
+ finally:
301
+ await source.close()
302
+ if not image_data:
303
+ raise HTTPException(status_code=400, detail={"error": "image file is empty"})
304
+ images.append((image_data, source.filename or "image.png", source.content_type or "image/png"))
305
+ continue
306
+ images.append(await run_in_threadpool(_download_image_url, source))
307
+ if not images:
308
+ raise HTTPException(status_code=400, detail={"error": "image file or image_url is required"})
309
+ return images