dsh-plugin-image-workbench 0.0.0-stage → 1.1.5

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +256 -0
  3. package/README.md +256 -2
  4. package/client.js +241 -0
  5. package/cordis.patch.yml +14 -0
  6. package/host.js +641 -0
  7. package/install.mjs +387 -0
  8. package/package.json +57 -4
  9. package/scripts/vendor-snapshot.py +154 -0
  10. package/server/access.py +26 -0
  11. package/server/app.py +1329 -0
  12. package/server/catalog.json +1 -0
  13. package/server/catalog.py +147 -0
  14. package/server/composer.py +391 -0
  15. package/server/drafts.py +158 -0
  16. package/server/history.py +575 -0
  17. package/server/imaging.py +172 -0
  18. package/server/pool.py +1335 -0
  19. package/server/pool_admin.py +921 -0
  20. package/server/pool_service.py +1073 -0
  21. package/server/requirements.txt +6 -0
  22. package/server/smoke_check.py +402 -0
  23. package/server/static/access.html +202 -0
  24. package/server/static/index.html +4725 -0
  25. package/vendor/chatgpt2api/README.md +13 -0
  26. package/vendor/chatgpt2api/SOURCE.json +11 -0
  27. package/vendor/chatgpt2api/runtime/uv.exe +0 -0
  28. package/vendor/chatgpt2api/source/.env.example +82 -0
  29. package/vendor/chatgpt2api/source/.python-version +1 -0
  30. package/vendor/chatgpt2api/source/LICENSE +21 -0
  31. package/vendor/chatgpt2api/source/README.md +391 -0
  32. package/vendor/chatgpt2api/source/VERSION +1 -0
  33. package/vendor/chatgpt2api/source/api/__init__.py +2 -0
  34. package/vendor/chatgpt2api/source/api/accounts.py +537 -0
  35. package/vendor/chatgpt2api/source/api/ai.py +217 -0
  36. package/vendor/chatgpt2api/source/api/app.py +62 -0
  37. package/vendor/chatgpt2api/source/api/errors.py +46 -0
  38. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -0
  39. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -0
  40. package/vendor/chatgpt2api/source/api/support.py +134 -0
  41. package/vendor/chatgpt2api/source/api/system.py +365 -0
  42. package/vendor/chatgpt2api/source/assets/atlascloud.svg +1 -0
  43. package/vendor/chatgpt2api/source/assets/ipwo.png +0 -0
  44. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -0
  45. package/vendor/chatgpt2api/source/config.default.json +108 -0
  46. package/vendor/chatgpt2api/source/main.py +9 -0
  47. package/vendor/chatgpt2api/source/pyproject.toml +27 -0
  48. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -0
  49. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -0
  50. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -0
  51. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -0
  52. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -0
  53. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -0
  54. package/vendor/chatgpt2api/source/services/__init__.py +0 -0
  55. package/vendor/chatgpt2api/source/services/account_service.py +1757 -0
  56. package/vendor/chatgpt2api/source/services/auth_service.py +253 -0
  57. package/vendor/chatgpt2api/source/services/backup_service.py +671 -0
  58. package/vendor/chatgpt2api/source/services/config.py +667 -0
  59. package/vendor/chatgpt2api/source/services/content_filter.py +242 -0
  60. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -0
  61. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -0
  62. package/vendor/chatgpt2api/source/services/image_service.py +376 -0
  63. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -0
  64. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -0
  65. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -0
  66. package/vendor/chatgpt2api/source/services/log_service.py +337 -0
  67. package/vendor/chatgpt2api/source/services/model_service.py +182 -0
  68. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -0
  69. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -0
  70. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -0
  71. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -0
  72. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -0
  73. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -0
  74. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -0
  75. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -0
  76. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -0
  77. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -0
  78. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -0
  79. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -0
  80. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -0
  81. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -0
  82. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -0
  83. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -0
  84. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -0
  85. package/vendor/chatgpt2api/source/services/storage/base.py +38 -0
  86. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -0
  87. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -0
  88. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -0
  89. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -0
  90. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -0
  91. package/vendor/chatgpt2api/source/utils/__init__.py +0 -0
  92. package/vendor/chatgpt2api/source/utils/helper.py +469 -0
  93. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -0
  94. package/vendor/chatgpt2api/source/utils/log.py +110 -0
  95. package/vendor/chatgpt2api/source/utils/pkce.py +19 -0
  96. package/vendor/chatgpt2api/source/utils/pow.py +207 -0
  97. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -0
  98. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -0
  99. package/vendor/chatgpt2api/source/uv.lock +904 -0
  100. package/vendor/chatgpt2api/source/web/bun.lock +1501 -0
  101. package/vendor/chatgpt2api/source/web/components.json +24 -0
  102. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -0
  103. package/vendor/chatgpt2api/source/web/next.config.ts +40 -0
  104. package/vendor/chatgpt2api/source/web/package.json +58 -0
  105. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -0
  106. package/vendor/chatgpt2api/source/web/public/github.svg +1 -0
  107. package/vendor/chatgpt2api/source/web/public/next.svg +1 -0
  108. package/vendor/chatgpt2api/source/web/public/openai.svg +1 -0
  109. package/vendor/chatgpt2api/source/web/public/vercel.svg +1 -0
  110. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -0
  111. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -0
  112. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -0
  113. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -0
  114. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -0
  115. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -0
  116. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -0
  117. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -0
  118. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -0
  119. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -0
  120. package/vendor/chatgpt2api/source/web/src/app/favicon.ico +0 -0
  121. package/vendor/chatgpt2api/source/web/src/app/globals.css +231 -0
  122. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -0
  123. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -0
  124. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -0
  125. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -0
  126. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -0
  127. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -0
  128. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -0
  129. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -0
  130. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -0
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -0
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -0
  133. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -0
  134. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -0
  135. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -0
  136. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -0
  137. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -0
  138. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -0
  139. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -0
  140. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -0
  141. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -0
  142. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -0
  143. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -0
  144. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -0
  145. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -0
  146. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -0
  147. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -0
  148. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -0
  149. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -0
  150. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -0
  151. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -0
  152. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -0
  153. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -0
  154. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -0
  155. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -0
  156. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -0
  157. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -0
  158. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -0
  159. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -0
  160. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -0
  161. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -0
  162. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -0
  163. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -0
  164. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -0
  165. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -0
  166. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -0
  167. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -0
  168. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -0
  169. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -0
  170. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -0
  171. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -0
  172. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -0
  173. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -0
  174. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -0
  175. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -0
  176. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -0
  177. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -0
  178. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -0
  179. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -0
  180. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -0
  181. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -0
  182. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -0
  183. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -0
  184. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -0
  185. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -0
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import APIRouter, Header, HTTPException, Request
4
+ from fastapi.concurrency import run_in_threadpool
5
+ from fastapi.responses import FileResponse
6
+ from pydantic import BaseModel, ConfigDict, Field
7
+
8
+ from api.image_inputs import parse_image_edit_request, read_image_sources
9
+ from api.support import require_identity, resolve_image_base_url
10
+ from services.content_filter import check_request, request_shape, request_text
11
+ from services.editable_file_task_service import editable_file_task_service
12
+ from services.log_service import LoggedCall
13
+ from services.protocol import (
14
+ anthropic_v1_messages,
15
+ openai_v1_chat_complete,
16
+ openai_v1_image_edit,
17
+ openai_v1_image_generations,
18
+ openai_v1_models,
19
+ openai_v1_response,
20
+ openai_search,
21
+ )
22
+
23
+
24
+ class ImageGenerationRequest(BaseModel):
25
+ prompt: str = Field(..., min_length=1)
26
+ model: str = "gpt-image-2"
27
+ n: int = Field(default=1, ge=1, le=4)
28
+ size: str | None = None
29
+ quality: str = "auto"
30
+ response_format: str = "b64_json"
31
+ history_disabled: bool = True
32
+ stream: bool | None = None
33
+
34
+
35
+ class ChatCompletionRequest(BaseModel):
36
+ model_config = ConfigDict(extra="allow")
37
+ model: str | None = None
38
+ prompt: str | None = None
39
+ n: int | None = None
40
+ stream: bool | None = None
41
+ modalities: list[str] | None = None
42
+ messages: list[dict[str, object]] | None = None
43
+
44
+
45
+ class ResponseCreateRequest(BaseModel):
46
+ model_config = ConfigDict(extra="allow")
47
+ model: str | None = None
48
+ input: object | None = None
49
+ tools: list[dict[str, object]] | None = None
50
+ tool_choice: object | None = None
51
+ stream: bool | None = None
52
+
53
+
54
+ class AnthropicMessageRequest(BaseModel):
55
+ model_config = ConfigDict(extra="allow")
56
+ model: str | None = None
57
+ messages: list[dict[str, object]] | None = None
58
+ system: object | None = None
59
+ stream: bool | None = None
60
+
61
+
62
+ class SearchRequest(BaseModel):
63
+ prompt: str = Field(..., min_length=1)
64
+
65
+
66
+ class EditableFileTaskRequest(BaseModel):
67
+ prompt: str = ""
68
+ base64_images: list[str] = Field(default_factory=list)
69
+ client_task_id: str | None = None
70
+
71
+
72
+ async def filter_or_log(call: LoggedCall, text: str) -> None:
73
+ try:
74
+ await run_in_threadpool(check_request, text)
75
+ except HTTPException as exc:
76
+ call.log("调用失败", status="failed", error=str(exc.detail))
77
+ raise
78
+
79
+
80
+ def create_router() -> APIRouter:
81
+ router = APIRouter()
82
+
83
+ @router.get("/v1/models")
84
+ async def list_models(authorization: str | None = Header(default=None)):
85
+ require_identity(authorization)
86
+ try:
87
+ return await run_in_threadpool(openai_v1_models.list_models)
88
+ except Exception as exc:
89
+ raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
90
+
91
+ @router.post("/v1/images/generations")
92
+ async def generate_images(
93
+ body: ImageGenerationRequest,
94
+ request: Request,
95
+ authorization: str | None = Header(default=None),
96
+ ):
97
+ identity = require_identity(authorization)
98
+ payload = body.model_dump(mode="python")
99
+ payload["base_url"] = resolve_image_base_url(request)
100
+ call = LoggedCall(identity, "/v1/images/generations", body.model, "文生图", request_text=body.prompt)
101
+ await filter_or_log(call, body.prompt)
102
+ return await call.run(openai_v1_image_generations.handle, payload)
103
+
104
+ @router.post("/v1/images/edits")
105
+ async def edit_images(
106
+ request: Request,
107
+ authorization: str | None = Header(default=None),
108
+ ):
109
+ identity = require_identity(authorization)
110
+ payload, image_sources, mask_sources = await parse_image_edit_request(request)
111
+ prompt = str(payload["prompt"])
112
+ model = str(payload["model"])
113
+ call = LoggedCall(identity, "/v1/images/edits", model, "图生图", request_text=prompt)
114
+ await filter_or_log(call, prompt)
115
+ payload["images"] = await read_image_sources(image_sources)
116
+ if mask_sources:
117
+ payload["mask"] = await read_image_sources(mask_sources)
118
+ payload["base_url"] = resolve_image_base_url(request)
119
+ return await call.run(openai_v1_image_edit.handle, payload)
120
+
121
+ @router.post("/v1/chat/completions")
122
+ async def create_chat_completion(body: ChatCompletionRequest, authorization: str | None = Header(default=None)):
123
+ identity = require_identity(authorization)
124
+ payload = body.model_dump(mode="python")
125
+ model = str(payload.get("model") or "auto")
126
+ request_preview = request_text(payload.get("prompt"), payload.get("messages"))
127
+ call = LoggedCall(
128
+ identity,
129
+ "/v1/chat/completions",
130
+ model,
131
+ "文本生成",
132
+ request_text=request_preview,
133
+ request_shape=request_shape(payload.get("messages")),
134
+ )
135
+ await filter_or_log(call, request_preview)
136
+ return await call.run(openai_v1_chat_complete.handle, payload)
137
+
138
+ @router.post("/v1/responses")
139
+ async def create_response(body: ResponseCreateRequest, authorization: str | None = Header(default=None)):
140
+ identity = require_identity(authorization)
141
+ payload = body.model_dump(mode="python")
142
+ model = str(payload.get("model") or "auto")
143
+ request_preview = request_text(payload.get("input"), payload.get("instructions"))
144
+ call = LoggedCall(
145
+ identity,
146
+ "/v1/responses",
147
+ model,
148
+ "Responses",
149
+ request_text=request_preview,
150
+ request_shape=request_shape(payload.get("input")),
151
+ )
152
+ await filter_or_log(call, request_preview)
153
+ return await call.run(openai_v1_response.handle, payload)
154
+
155
+ @router.post("/v1/messages")
156
+ async def create_message(
157
+ body: AnthropicMessageRequest,
158
+ authorization: str | None = Header(default=None),
159
+ x_api_key: str | None = Header(default=None, alias="x-api-key"),
160
+ anthropic_version: str | None = Header(default=None, alias="anthropic-version"),
161
+ ):
162
+ identity = require_identity(authorization or (f"Bearer {x_api_key}" if x_api_key else None))
163
+ payload = body.model_dump(mode="python")
164
+ model = str(payload.get("model") or "auto")
165
+ request_preview = request_text(payload.get("system"), payload.get("messages"), payload.get("tools"))
166
+ call = LoggedCall(identity, "/v1/messages", model, "Messages", request_text=request_preview)
167
+ await filter_or_log(call, request_preview)
168
+ return await call.run(anthropic_v1_messages.handle, payload, sse="anthropic")
169
+
170
+ @router.post("/v1/search")
171
+ async def search(body: SearchRequest, authorization: str | None = Header(default=None)):
172
+ identity = require_identity(authorization)
173
+ call = LoggedCall(identity, "/v1/search", openai_search.MODEL, "搜索", request_text=body.prompt)
174
+ await filter_or_log(call, body.prompt)
175
+ return await call.run(openai_search.handle, body.model_dump(mode="python"))
176
+
177
+ @router.get("/v1/editable-file-tasks")
178
+ async def list_editable_file_tasks(ids: str = "", authorization: str | None = Header(default=None)):
179
+ identity = require_identity(authorization)
180
+ task_ids = [item.strip() for item in ids.split(",") if item.strip()]
181
+ return await run_in_threadpool(editable_file_task_service.list_tasks, identity, task_ids)
182
+
183
+ @router.get("/files/{file_path:path}")
184
+ async def download_editable_file(file_path: str):
185
+ try:
186
+ path = await run_in_threadpool(editable_file_task_service.public_file_path, file_path)
187
+ except Exception as exc:
188
+ raise HTTPException(status_code=404, detail={"error": "file not found"}) from exc
189
+ return FileResponse(path, filename=path.name)
190
+
191
+ @router.post("/v1/ppt/generations")
192
+ async def create_ppt_task(body: EditableFileTaskRequest, request: Request, authorization: str | None = Header(default=None)):
193
+ identity = require_identity(authorization)
194
+ await filter_or_log(LoggedCall(identity, "/v1/ppt/generations", "gpt-5-5-thinking", "PPT生成任务", request_text=body.prompt), body.prompt)
195
+ return await run_in_threadpool(
196
+ editable_file_task_service.submit_ppt,
197
+ identity,
198
+ client_task_id=body.client_task_id or "",
199
+ prompt=body.prompt,
200
+ base64_images=body.base64_images,
201
+ base_url=resolve_image_base_url(request),
202
+ )
203
+
204
+ @router.post("/v1/psd/generations")
205
+ async def create_psd_task(body: EditableFileTaskRequest, request: Request, authorization: str | None = Header(default=None)):
206
+ identity = require_identity(authorization)
207
+ await filter_or_log(LoggedCall(identity, "/v1/psd/generations", "gpt-5-5-thinking", "PSD生成任务", request_text=body.prompt), body.prompt)
208
+ return await run_in_threadpool(
209
+ editable_file_task_service.submit_psd,
210
+ identity,
211
+ client_task_id=body.client_task_id or "",
212
+ prompt=body.prompt,
213
+ base64_images=body.base64_images,
214
+ base_url=resolve_image_base_url(request),
215
+ )
216
+
217
+ return router
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import asynccontextmanager
4
+ from threading import Event
5
+
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import FileResponse
9
+
10
+ from api import accounts, ai, image_tasks, system
11
+ from api.errors import install_exception_handlers
12
+ from api.support import resolve_web_asset, start_limited_account_watcher
13
+ from services.backup_service import backup_service
14
+ from services.config import config
15
+ from services.image_service import start_image_cleanup_scheduler
16
+
17
+
18
+ def create_app() -> FastAPI:
19
+ app_version = config.app_version
20
+
21
+ @asynccontextmanager
22
+ async def lifespan(_: FastAPI):
23
+ stop_event = Event()
24
+ thread = start_limited_account_watcher(stop_event)
25
+ cleanup_thread = start_image_cleanup_scheduler(stop_event)
26
+ backup_service.start()
27
+ config.cleanup_old_images()
28
+ try:
29
+ yield
30
+ finally:
31
+ stop_event.set()
32
+ thread.join(timeout=1)
33
+ cleanup_thread.join(timeout=1)
34
+ backup_service.stop()
35
+
36
+ app = FastAPI(title="chatgpt2api", version=app_version, lifespan=lifespan)
37
+ install_exception_handlers(app)
38
+ app.add_middleware(
39
+ CORSMiddleware,
40
+ allow_origins=["*"],
41
+ allow_credentials=False,
42
+ allow_methods=["*"],
43
+ allow_headers=["*"],
44
+ )
45
+ app.include_router(ai.create_router())
46
+ app.include_router(accounts.create_router())
47
+ app.include_router(image_tasks.create_router())
48
+ app.include_router(system.create_router(app_version))
49
+
50
+ @app.api_route("/{full_path:path}", methods=["GET", "HEAD"], include_in_schema=False)
51
+ async def serve_web(full_path: str):
52
+ asset = resolve_web_asset(full_path)
53
+ if asset is not None:
54
+ return FileResponse(asset)
55
+ if full_path.strip("/").startswith("_next/"):
56
+ raise HTTPException(status_code=404, detail="Not Found")
57
+ fallback = resolve_web_asset("")
58
+ if fallback is None:
59
+ raise HTTPException(status_code=404, detail="Not Found")
60
+ return FileResponse(fallback)
61
+
62
+ return app
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.encoders import jsonable_encoder
5
+ from fastapi.exceptions import RequestValidationError
6
+ from fastapi.responses import JSONResponse
7
+ from starlette.exceptions import HTTPException as StarletteHTTPException
8
+
9
+ from services.protocol.error_response import anthropic_error_response, openai_error_response
10
+
11
+
12
+ def _is_openai_compatible_path(path: str) -> bool:
13
+ return path == "/v1" or path.startswith("/v1/")
14
+
15
+
16
+ def _is_anthropic_messages_path(path: str) -> bool:
17
+ return path == "/v1/messages"
18
+
19
+
20
+ def _compatible_error_response(
21
+ request: Request,
22
+ detail: object,
23
+ status_code: int,
24
+ headers: dict[str, str] | None = None,
25
+ ) -> JSONResponse:
26
+ if _is_anthropic_messages_path(request.url.path):
27
+ return anthropic_error_response(detail, status_code, headers=headers)
28
+ return openai_error_response(detail, status_code, headers=headers)
29
+
30
+
31
+ def install_exception_handlers(app: FastAPI) -> None:
32
+ @app.exception_handler(StarletteHTTPException)
33
+ async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
34
+ if _is_openai_compatible_path(request.url.path):
35
+ return _compatible_error_response(request, exc.detail, exc.status_code, exc.headers)
36
+ return JSONResponse(
37
+ status_code=exc.status_code,
38
+ content={"detail": jsonable_encoder(exc.detail)},
39
+ headers=exc.headers,
40
+ )
41
+
42
+ @app.exception_handler(RequestValidationError)
43
+ async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
44
+ if _is_openai_compatible_path(request.url.path):
45
+ return _compatible_error_response(request, exc.errors(), 422)
46
+ return JSONResponse(status_code=422, content={"detail": jsonable_encoder(exc.errors())})
@@ -0,0 +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