Merge branch 'basketikun:main' into main
Browse files- .gitignore +3 -1
- pyproject.toml +1 -0
- services/api.py +30 -1
- services/chatgpt_service.py +84 -3
- services/image_service.py +297 -0
- services/utils.py +43 -0
- uv.lock +0 -0
- web/src/app/image/components/image-composer.tsx +224 -0
- web/src/app/image/components/image-results.tsx +147 -0
- web/src/app/image/components/image-sidebar.tsx +101 -0
- web/src/app/image/page.tsx +131 -266
- web/src/lib/api.ts +16 -0
- web/src/store/image-conversations.ts +11 -0
.gitignore
CHANGED
|
@@ -5,11 +5,13 @@ build/
|
|
| 5 |
dist/
|
| 6 |
wheels/
|
| 7 |
*.egg-info
|
| 8 |
-
|
| 9 |
# Virtual environments
|
| 10 |
.venv
|
| 11 |
.idea
|
| 12 |
data
|
| 13 |
config.json
|
|
|
|
|
|
|
| 14 |
|
| 15 |
docker-compose-local.yml
|
|
|
|
| 5 |
dist/
|
| 6 |
wheels/
|
| 7 |
*.egg-info
|
| 8 |
+
web_dist
|
| 9 |
# Virtual environments
|
| 10 |
.venv
|
| 11 |
.idea
|
| 12 |
data
|
| 13 |
config.json
|
| 14 |
+
edit
|
| 15 |
+
test
|
| 16 |
|
| 17 |
docker-compose-local.yml
|
pyproject.toml
CHANGED
|
@@ -8,5 +8,6 @@ dependencies = [
|
|
| 8 |
"curl-cffi>=0.15.0",
|
| 9 |
"fastapi>=0.136.0",
|
| 10 |
"pybase64>=1.4.3",
|
|
|
|
| 11 |
"uvicorn>=0.44.0",
|
| 12 |
]
|
|
|
|
| 8 |
"curl-cffi>=0.15.0",
|
| 9 |
"fastapi>=0.136.0",
|
| 10 |
"pybase64>=1.4.3",
|
| 11 |
+
"python-multipart>=0.0.26",
|
| 12 |
"uvicorn>=0.44.0",
|
| 13 |
]
|
services/api.py
CHANGED
|
@@ -4,7 +4,7 @@ from contextlib import asynccontextmanager
|
|
| 4 |
from pathlib import Path
|
| 5 |
from threading import Event, Thread
|
| 6 |
|
| 7 |
-
from fastapi import APIRouter, FastAPI, Header, HTTPException
|
| 8 |
from fastapi.concurrency import run_in_threadpool
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from fastapi.responses import FileResponse
|
|
@@ -279,6 +279,35 @@ def create_app() -> FastAPI:
|
|
| 279 |
except ImageGenerationError as exc:
|
| 280 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 281 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
@router.post("/v1/chat/completions")
|
| 283 |
async def create_chat_completion(body: ChatCompletionRequest, authorization: str | None = Header(default=None)):
|
| 284 |
require_auth_key(authorization)
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
from threading import Event, Thread
|
| 6 |
|
| 7 |
+
from fastapi import APIRouter, FastAPI, File, Form, Header, HTTPException, UploadFile
|
| 8 |
from fastapi.concurrency import run_in_threadpool
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from fastapi.responses import FileResponse
|
|
|
|
| 279 |
except ImageGenerationError as exc:
|
| 280 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 281 |
|
| 282 |
+
@router.post("/v1/images/edits")
|
| 283 |
+
async def edit_images(
|
| 284 |
+
authorization: str | None = Header(default=None),
|
| 285 |
+
image: UploadFile | None = File(default=None),
|
| 286 |
+
prompt: str = Form(...),
|
| 287 |
+
model: str = Form(default="gpt-image-1"),
|
| 288 |
+
n: int = Form(default=1),
|
| 289 |
+
):
|
| 290 |
+
require_auth_key(authorization)
|
| 291 |
+
if n < 1 or n > 4:
|
| 292 |
+
raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
|
| 293 |
+
|
| 294 |
+
if image is None:
|
| 295 |
+
raise HTTPException(status_code=400, detail={"error": "image file is required"})
|
| 296 |
+
|
| 297 |
+
image_data = await image.read()
|
| 298 |
+
if not image_data:
|
| 299 |
+
raise HTTPException(status_code=400, detail={"error": "image file is empty"})
|
| 300 |
+
|
| 301 |
+
file_name = image.filename or "image.png"
|
| 302 |
+
mime_type = image.content_type or "image/png"
|
| 303 |
+
|
| 304 |
+
try:
|
| 305 |
+
return await run_in_threadpool(
|
| 306 |
+
chatgpt_service.edit_with_pool, prompt, image_data, file_name, mime_type, model, n
|
| 307 |
+
)
|
| 308 |
+
except ImageGenerationError as exc:
|
| 309 |
+
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 310 |
+
|
| 311 |
@router.post("/v1/chat/completions")
|
| 312 |
async def create_chat_completion(body: ChatCompletionRequest, authorization: str | None = Header(default=None)):
|
| 313 |
require_auth_key(authorization)
|
services/chatgpt_service.py
CHANGED
|
@@ -3,10 +3,12 @@ from __future__ import annotations
|
|
| 3 |
from fastapi import HTTPException
|
| 4 |
|
| 5 |
from services.account_service import AccountService
|
| 6 |
-
from services.image_service import ImageGenerationError, generate_image_result, is_token_invalid_error
|
| 7 |
from services.utils import (
|
| 8 |
build_chat_image_completion,
|
|
|
|
| 9 |
extract_chat_prompt,
|
|
|
|
| 10 |
extract_response_prompt,
|
| 11 |
has_response_image_generation_tool,
|
| 12 |
is_image_chat_request,
|
|
@@ -14,6 +16,28 @@ from services.utils import (
|
|
| 14 |
)
|
| 15 |
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
class ChatGPTService:
|
| 18 |
def __init__(self, account_service: AccountService):
|
| 19 |
self.account_service = account_service
|
|
@@ -65,6 +89,53 @@ class ChatGPTService:
|
|
| 65 |
"data": image_items,
|
| 66 |
}
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def create_image_completion(self, body: dict[str, object]) -> dict[str, object]:
|
| 69 |
if not is_image_chat_request(body):
|
| 70 |
raise HTTPException(
|
|
@@ -81,8 +152,13 @@ class ChatGPTService:
|
|
| 81 |
if not prompt:
|
| 82 |
raise HTTPException(status_code=400, detail={"error": "prompt is required"})
|
| 83 |
|
|
|
|
| 84 |
try:
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except ImageGenerationError as exc:
|
| 87 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 88 |
|
|
@@ -102,9 +178,14 @@ class ChatGPTService:
|
|
| 102 |
if not prompt:
|
| 103 |
raise HTTPException(status_code=400, detail={"error": "input text is required"})
|
| 104 |
|
|
|
|
| 105 |
model = str(body.get("model") or "gpt-5").strip() or "gpt-5"
|
| 106 |
try:
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
except ImageGenerationError as exc:
|
| 109 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 110 |
|
|
|
|
| 3 |
from fastapi import HTTPException
|
| 4 |
|
| 5 |
from services.account_service import AccountService
|
| 6 |
+
from services.image_service import ImageGenerationError, edit_image_result, generate_image_result, is_token_invalid_error
|
| 7 |
from services.utils import (
|
| 8 |
build_chat_image_completion,
|
| 9 |
+
extract_chat_image,
|
| 10 |
extract_chat_prompt,
|
| 11 |
+
extract_image_from_message_content,
|
| 12 |
extract_response_prompt,
|
| 13 |
has_response_image_generation_tool,
|
| 14 |
is_image_chat_request,
|
|
|
|
| 16 |
)
|
| 17 |
|
| 18 |
|
| 19 |
+
def _extract_response_image(input_value: object) -> tuple[bytes, str] | None:
|
| 20 |
+
if isinstance(input_value, dict):
|
| 21 |
+
return extract_image_from_message_content(input_value.get("content"))
|
| 22 |
+
if not isinstance(input_value, list):
|
| 23 |
+
return None
|
| 24 |
+
for item in reversed(input_value):
|
| 25 |
+
if isinstance(item, dict):
|
| 26 |
+
if str(item.get("type") or "").strip() == "input_image":
|
| 27 |
+
import base64 as b64
|
| 28 |
+
image_url = str(item.get("image_url") or "")
|
| 29 |
+
if image_url.startswith("data:"):
|
| 30 |
+
header, _, data = image_url.partition(",")
|
| 31 |
+
mime = header.split(";")[0].removeprefix("data:")
|
| 32 |
+
return b64.b64decode(data), mime or "image/png"
|
| 33 |
+
content = item.get("content")
|
| 34 |
+
if content:
|
| 35 |
+
result = extract_image_from_message_content(content)
|
| 36 |
+
if result:
|
| 37 |
+
return result
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
class ChatGPTService:
|
| 42 |
def __init__(self, account_service: AccountService):
|
| 43 |
self.account_service = account_service
|
|
|
|
| 89 |
"data": image_items,
|
| 90 |
}
|
| 91 |
|
| 92 |
+
def edit_with_pool(self, prompt: str, image_data: bytes, file_name: str, mime_type: str, model: str, n: int):
|
| 93 |
+
created = None
|
| 94 |
+
image_items: list[dict[str, object]] = []
|
| 95 |
+
|
| 96 |
+
for index in range(1, n + 1):
|
| 97 |
+
while True:
|
| 98 |
+
try:
|
| 99 |
+
request_token = self.account_service.get_available_access_token()
|
| 100 |
+
except RuntimeError as exc:
|
| 101 |
+
print(f"[image-edit] stop index={index}/{n} error={exc}")
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
print(f"[image-edit] start pooled token={request_token[:12]}... model={model} index={index}/{n}")
|
| 105 |
+
try:
|
| 106 |
+
result = edit_image_result(request_token, prompt, image_data, file_name, mime_type, model)
|
| 107 |
+
account = self.account_service.mark_image_result(request_token, success=True)
|
| 108 |
+
if created is None:
|
| 109 |
+
created = result.get("created")
|
| 110 |
+
data = result.get("data")
|
| 111 |
+
if isinstance(data, list):
|
| 112 |
+
image_items.extend(item for item in data if isinstance(item, dict))
|
| 113 |
+
print(
|
| 114 |
+
f"[image-edit] success pooled token={request_token[:12]}... "
|
| 115 |
+
f"quota={account.get('quota') if account else 'unknown'} status={account.get('status') if account else 'unknown'}"
|
| 116 |
+
)
|
| 117 |
+
break
|
| 118 |
+
except ImageGenerationError as exc:
|
| 119 |
+
account = self.account_service.mark_image_result(request_token, success=False)
|
| 120 |
+
message = str(exc)
|
| 121 |
+
print(
|
| 122 |
+
f"[image-edit] fail pooled token={request_token[:12]}... "
|
| 123 |
+
f"error={message} quota={account.get('quota') if account else 'unknown'} status={account.get('status') if account else 'unknown'}"
|
| 124 |
+
)
|
| 125 |
+
if is_token_invalid_error(message):
|
| 126 |
+
self.account_service.remove_token(request_token)
|
| 127 |
+
print(f"[image-edit] remove invalid token={request_token[:12]}...")
|
| 128 |
+
continue
|
| 129 |
+
break
|
| 130 |
+
|
| 131 |
+
if not image_items:
|
| 132 |
+
raise ImageGenerationError("image edit failed")
|
| 133 |
+
|
| 134 |
+
return {
|
| 135 |
+
"created": created,
|
| 136 |
+
"data": image_items,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
def create_image_completion(self, body: dict[str, object]) -> dict[str, object]:
|
| 140 |
if not is_image_chat_request(body):
|
| 141 |
raise HTTPException(
|
|
|
|
| 152 |
if not prompt:
|
| 153 |
raise HTTPException(status_code=400, detail={"error": "prompt is required"})
|
| 154 |
|
| 155 |
+
image_info = extract_chat_image(body)
|
| 156 |
try:
|
| 157 |
+
if image_info:
|
| 158 |
+
image_data, mime_type = image_info
|
| 159 |
+
image_result = self.edit_with_pool(prompt, image_data, "image.png", mime_type, model, n)
|
| 160 |
+
else:
|
| 161 |
+
image_result = self.generate_with_pool(prompt, model, n)
|
| 162 |
except ImageGenerationError as exc:
|
| 163 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 164 |
|
|
|
|
| 178 |
if not prompt:
|
| 179 |
raise HTTPException(status_code=400, detail={"error": "input text is required"})
|
| 180 |
|
| 181 |
+
image_info = _extract_response_image(body.get("input"))
|
| 182 |
model = str(body.get("model") or "gpt-5").strip() or "gpt-5"
|
| 183 |
try:
|
| 184 |
+
if image_info:
|
| 185 |
+
image_data, mime_type = image_info
|
| 186 |
+
image_result = self.edit_with_pool(prompt, image_data, "image.png", mime_type, "gpt-image-1", 1)
|
| 187 |
+
else:
|
| 188 |
+
image_result = self.generate_with_pool(prompt, "gpt-image-1", 1)
|
| 189 |
except ImageGenerationError as exc:
|
| 190 |
raise HTTPException(status_code=502, detail={"error": str(exc)}) from exc
|
| 191 |
|
services/image_service.py
CHANGED
|
@@ -211,6 +211,180 @@ def is_token_invalid_error(message: str) -> bool:
|
|
| 211 |
)
|
| 212 |
|
| 213 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
def _send_conversation(
|
| 215 |
session: Session,
|
| 216 |
access_token: str,
|
|
@@ -507,3 +681,126 @@ def generate_image_result(access_token: str, prompt: str, model: str = DEFAULT_M
|
|
| 507 |
raise
|
| 508 |
finally:
|
| 509 |
session.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
)
|
| 212 |
|
| 213 |
|
| 214 |
+
def _upload_image(session: Session, access_token: str, device_id: str, image_data: bytes, file_name: str, mime_type: str) -> str:
|
| 215 |
+
response = _retry(
|
| 216 |
+
lambda: session.post(
|
| 217 |
+
BASE_URL + "/backend-api/files",
|
| 218 |
+
headers={
|
| 219 |
+
"Authorization": f"Bearer {access_token}",
|
| 220 |
+
"oai-device-id": device_id,
|
| 221 |
+
"content-type": "application/json",
|
| 222 |
+
},
|
| 223 |
+
json={
|
| 224 |
+
"file_name": file_name,
|
| 225 |
+
"file_size": len(image_data),
|
| 226 |
+
"use_case": "multimodal",
|
| 227 |
+
"timezone_offset_min": -480,
|
| 228 |
+
"reset_rate_limits": False,
|
| 229 |
+
},
|
| 230 |
+
timeout=30,
|
| 231 |
+
),
|
| 232 |
+
retries=3,
|
| 233 |
+
)
|
| 234 |
+
if not response.ok:
|
| 235 |
+
raise ImageGenerationError(f"file upload init failed: {response.status_code} {response.text[:200]}")
|
| 236 |
+
payload = response.json()
|
| 237 |
+
upload_url = payload.get("upload_url") or ""
|
| 238 |
+
file_id = payload.get("file_id") or ""
|
| 239 |
+
if not upload_url or not file_id:
|
| 240 |
+
raise ImageGenerationError("file upload init returned no upload_url or file_id")
|
| 241 |
+
|
| 242 |
+
put_resp = _retry(
|
| 243 |
+
lambda: session.put(
|
| 244 |
+
upload_url,
|
| 245 |
+
headers={
|
| 246 |
+
"Content-Type": mime_type,
|
| 247 |
+
"x-ms-blob-type": "BlockBlob",
|
| 248 |
+
"x-ms-version": "2020-04-08",
|
| 249 |
+
},
|
| 250 |
+
data=image_data,
|
| 251 |
+
timeout=60,
|
| 252 |
+
),
|
| 253 |
+
retries=3,
|
| 254 |
+
)
|
| 255 |
+
if not (200 <= put_resp.status_code < 300):
|
| 256 |
+
raise ImageGenerationError(f"file upload PUT failed: {put_resp.status_code}")
|
| 257 |
+
|
| 258 |
+
process_resp = _retry(
|
| 259 |
+
lambda: session.post(
|
| 260 |
+
BASE_URL + "/backend-api/files/process_upload_stream",
|
| 261 |
+
headers={
|
| 262 |
+
"Authorization": f"Bearer {access_token}",
|
| 263 |
+
"oai-device-id": device_id,
|
| 264 |
+
"content-type": "application/json",
|
| 265 |
+
},
|
| 266 |
+
json={
|
| 267 |
+
"file_id": file_id,
|
| 268 |
+
"use_case": "multimodal",
|
| 269 |
+
"index_for_retrieval": False,
|
| 270 |
+
"file_name": file_name,
|
| 271 |
+
},
|
| 272 |
+
timeout=30,
|
| 273 |
+
),
|
| 274 |
+
retries=3,
|
| 275 |
+
)
|
| 276 |
+
if not process_resp.ok:
|
| 277 |
+
raise ImageGenerationError(f"file process failed: {process_resp.status_code}")
|
| 278 |
+
return file_id
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _send_edit_conversation(
|
| 282 |
+
session: Session,
|
| 283 |
+
access_token: str,
|
| 284 |
+
device_id: str,
|
| 285 |
+
chat_token: str,
|
| 286 |
+
proof_token: Optional[str],
|
| 287 |
+
parent_message_id: str,
|
| 288 |
+
prompt: str,
|
| 289 |
+
model: str,
|
| 290 |
+
file_id: str,
|
| 291 |
+
image_size: int,
|
| 292 |
+
image_width: int,
|
| 293 |
+
image_height: int,
|
| 294 |
+
file_name: str,
|
| 295 |
+
mime_type: str,
|
| 296 |
+
):
|
| 297 |
+
headers = {
|
| 298 |
+
"Authorization": f"Bearer {access_token}",
|
| 299 |
+
"accept": "text/event-stream",
|
| 300 |
+
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
|
| 301 |
+
"content-type": "application/json",
|
| 302 |
+
"oai-device-id": device_id,
|
| 303 |
+
"oai-language": "zh-CN",
|
| 304 |
+
"oai-client-build-number": "5955942",
|
| 305 |
+
"oai-client-version": "prod-be885abbfcfe7b1f511e88b3003d9ee44757fbad",
|
| 306 |
+
"origin": BASE_URL,
|
| 307 |
+
"referer": BASE_URL + "/",
|
| 308 |
+
"openai-sentinel-chat-requirements-token": chat_token,
|
| 309 |
+
}
|
| 310 |
+
if proof_token:
|
| 311 |
+
headers["openai-sentinel-proof-token"] = proof_token
|
| 312 |
+
response = _retry(
|
| 313 |
+
lambda: session.post(
|
| 314 |
+
BASE_URL + "/backend-api/conversation",
|
| 315 |
+
headers=headers,
|
| 316 |
+
json={
|
| 317 |
+
"action": "next",
|
| 318 |
+
"messages": [
|
| 319 |
+
{
|
| 320 |
+
"id": str(uuid.uuid4()),
|
| 321 |
+
"author": {"role": "user"},
|
| 322 |
+
"content": {
|
| 323 |
+
"content_type": "multimodal_text",
|
| 324 |
+
"parts": [
|
| 325 |
+
{
|
| 326 |
+
"content_type": "image_asset_pointer",
|
| 327 |
+
"asset_pointer": f"sediment://{file_id}",
|
| 328 |
+
"size_bytes": image_size,
|
| 329 |
+
"width": image_width,
|
| 330 |
+
"height": image_height,
|
| 331 |
+
},
|
| 332 |
+
prompt,
|
| 333 |
+
],
|
| 334 |
+
},
|
| 335 |
+
"metadata": {
|
| 336 |
+
"attachments": [
|
| 337 |
+
{
|
| 338 |
+
"id": file_id,
|
| 339 |
+
"size": image_size,
|
| 340 |
+
"name": file_name,
|
| 341 |
+
"mime_type": mime_type,
|
| 342 |
+
"width": image_width,
|
| 343 |
+
"height": image_height,
|
| 344 |
+
"source": "local",
|
| 345 |
+
"is_big_paste": False,
|
| 346 |
+
}
|
| 347 |
+
],
|
| 348 |
+
},
|
| 349 |
+
}
|
| 350 |
+
],
|
| 351 |
+
"parent_message_id": parent_message_id,
|
| 352 |
+
"model": model,
|
| 353 |
+
"history_and_training_disabled": False,
|
| 354 |
+
"timezone_offset_min": -480,
|
| 355 |
+
"timezone": "America/Los_Angeles",
|
| 356 |
+
"conversation_mode": {"kind": "primary_assistant"},
|
| 357 |
+
"force_paragen": False,
|
| 358 |
+
"force_paragen_model_slug": "",
|
| 359 |
+
"force_rate_limit": False,
|
| 360 |
+
"force_use_sse": True,
|
| 361 |
+
"paragen_cot_summary_display_override": "allow",
|
| 362 |
+
"reset_rate_limits": False,
|
| 363 |
+
"suggestions": [],
|
| 364 |
+
"supported_encodings": [],
|
| 365 |
+
"system_hints": ["picture_v2"],
|
| 366 |
+
"variant_purpose": "comparison_implicit",
|
| 367 |
+
"websocket_request_id": str(uuid.uuid4()),
|
| 368 |
+
"client_contextual_info": {
|
| 369 |
+
"is_dark_mode": False,
|
| 370 |
+
"time_since_loaded": random.randint(50, 500),
|
| 371 |
+
"page_height": random.randint(500, 1000),
|
| 372 |
+
"page_width": random.randint(1000, 2000),
|
| 373 |
+
"pixel_ratio": 1.2,
|
| 374 |
+
"screen_height": random.randint(800, 1200),
|
| 375 |
+
"screen_width": random.randint(1200, 2200),
|
| 376 |
+
},
|
| 377 |
+
},
|
| 378 |
+
stream=True,
|
| 379 |
+
timeout=180,
|
| 380 |
+
),
|
| 381 |
+
retries=3,
|
| 382 |
+
)
|
| 383 |
+
if not response.ok:
|
| 384 |
+
raise ImageGenerationError(response.text[:400] or f"conversation failed: {response.status_code}")
|
| 385 |
+
return response
|
| 386 |
+
|
| 387 |
+
|
| 388 |
def _send_conversation(
|
| 389 |
session: Session,
|
| 390 |
access_token: str,
|
|
|
|
| 681 |
raise
|
| 682 |
finally:
|
| 683 |
session.close()
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _get_image_dimensions(image_data: bytes) -> tuple[int, int]:
|
| 687 |
+
if image_data[:8] == b"\x89PNG\r\n\x1a\n" and len(image_data) >= 24:
|
| 688 |
+
import struct
|
| 689 |
+
w, h = struct.unpack(">II", image_data[16:24])
|
| 690 |
+
return w, h
|
| 691 |
+
if image_data[:2] in (b"\xff\xd8",):
|
| 692 |
+
import io
|
| 693 |
+
data = io.BytesIO(image_data)
|
| 694 |
+
data.read(2)
|
| 695 |
+
while True:
|
| 696 |
+
marker = data.read(2)
|
| 697 |
+
if len(marker) < 2:
|
| 698 |
+
break
|
| 699 |
+
if marker[0] != 0xFF:
|
| 700 |
+
break
|
| 701 |
+
if marker[1] in (0xC0, 0xC1, 0xC2):
|
| 702 |
+
data.read(3)
|
| 703 |
+
h_bytes = data.read(2)
|
| 704 |
+
w_bytes = data.read(2)
|
| 705 |
+
if len(h_bytes) == 2 and len(w_bytes) == 2:
|
| 706 |
+
import struct
|
| 707 |
+
h = struct.unpack(">H", h_bytes)[0]
|
| 708 |
+
w = struct.unpack(">H", w_bytes)[0]
|
| 709 |
+
return w, h
|
| 710 |
+
break
|
| 711 |
+
else:
|
| 712 |
+
length_bytes = data.read(2)
|
| 713 |
+
if len(length_bytes) < 2:
|
| 714 |
+
break
|
| 715 |
+
import struct
|
| 716 |
+
length = struct.unpack(">H", length_bytes)[0]
|
| 717 |
+
data.read(length - 2)
|
| 718 |
+
return 1024, 1024
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def edit_image_result(
|
| 722 |
+
access_token: str,
|
| 723 |
+
prompt: str,
|
| 724 |
+
image_data: bytes,
|
| 725 |
+
file_name: str = "image.png",
|
| 726 |
+
mime_type: str = "image/png",
|
| 727 |
+
model: str = DEFAULT_MODEL,
|
| 728 |
+
) -> dict:
|
| 729 |
+
prompt = str(prompt or "").strip()
|
| 730 |
+
access_token = str(access_token or "").strip()
|
| 731 |
+
if not prompt:
|
| 732 |
+
raise ImageGenerationError("prompt is required")
|
| 733 |
+
if not access_token:
|
| 734 |
+
raise ImageGenerationError("token is required")
|
| 735 |
+
if not image_data:
|
| 736 |
+
raise ImageGenerationError("image is required")
|
| 737 |
+
|
| 738 |
+
session, fp = _new_session(access_token)
|
| 739 |
+
try:
|
| 740 |
+
upstream_model = _resolve_upstream_model(access_token, model)
|
| 741 |
+
print(
|
| 742 |
+
f"[image-edit-upstream] start token={access_token[:12]}... "
|
| 743 |
+
f"requested_model={model} upstream_model={upstream_model}"
|
| 744 |
+
)
|
| 745 |
+
device_id = _bootstrap(session, fp)
|
| 746 |
+
|
| 747 |
+
file_id = _upload_image(session, access_token, device_id, image_data, file_name, mime_type)
|
| 748 |
+
print(f"[image-edit-upstream] uploaded file_id={file_id}")
|
| 749 |
+
|
| 750 |
+
image_width, image_height = _get_image_dimensions(image_data)
|
| 751 |
+
|
| 752 |
+
chat_token, pow_info = _chat_requirements(session, access_token, device_id)
|
| 753 |
+
proof_token = None
|
| 754 |
+
if pow_info.get("required"):
|
| 755 |
+
proof_token = _generate_proof_token(
|
| 756 |
+
seed=str(pow_info["seed"]),
|
| 757 |
+
difficulty=str(pow_info["difficulty"]),
|
| 758 |
+
user_agent=USER_AGENT,
|
| 759 |
+
proof_config=_pow_config(USER_AGENT),
|
| 760 |
+
)
|
| 761 |
+
parent_message_id = str(uuid.uuid4())
|
| 762 |
+
response = _send_edit_conversation(
|
| 763 |
+
session,
|
| 764 |
+
access_token,
|
| 765 |
+
device_id,
|
| 766 |
+
chat_token,
|
| 767 |
+
proof_token,
|
| 768 |
+
parent_message_id,
|
| 769 |
+
prompt,
|
| 770 |
+
upstream_model,
|
| 771 |
+
file_id,
|
| 772 |
+
len(image_data),
|
| 773 |
+
image_width,
|
| 774 |
+
image_height,
|
| 775 |
+
file_name,
|
| 776 |
+
mime_type,
|
| 777 |
+
)
|
| 778 |
+
parsed = _parse_sse(response)
|
| 779 |
+
actual_conversation_id = parsed.get("conversation_id") or ""
|
| 780 |
+
file_ids = parsed.get("file_ids") or []
|
| 781 |
+
response_text = str(parsed.get("text") or "").strip()
|
| 782 |
+
if actual_conversation_id and not file_ids:
|
| 783 |
+
file_ids = _poll_image_ids(session, access_token, device_id, actual_conversation_id)
|
| 784 |
+
if not file_ids:
|
| 785 |
+
if response_text:
|
| 786 |
+
raise ImageGenerationError(response_text)
|
| 787 |
+
raise ImageGenerationError("no image returned from upstream")
|
| 788 |
+
first_file_id = str(file_ids[0])
|
| 789 |
+
download_url = _fetch_download_url(session, access_token, device_id, actual_conversation_id, first_file_id)
|
| 790 |
+
if not download_url:
|
| 791 |
+
raise ImageGenerationError("failed to get download url")
|
| 792 |
+
result = GeneratedImage(
|
| 793 |
+
b64_json=_download_as_base64(session, download_url),
|
| 794 |
+
revised_prompt=prompt,
|
| 795 |
+
url=download_url,
|
| 796 |
+
)
|
| 797 |
+
print(f"[image-edit-upstream] success token={access_token[:12]}... images=1")
|
| 798 |
+
return {
|
| 799 |
+
"created": time.time_ns() // 1_000_000_000,
|
| 800 |
+
"data": [{"b64_json": result.b64_json, "revised_prompt": result.revised_prompt}],
|
| 801 |
+
}
|
| 802 |
+
except Exception as exc:
|
| 803 |
+
print(f"[image-edit-upstream] fail token={access_token[:12]}... error={exc}")
|
| 804 |
+
raise
|
| 805 |
+
finally:
|
| 806 |
+
session.close()
|
services/utils.py
CHANGED
|
@@ -87,6 +87,49 @@ def extract_prompt_from_message_content(content: object) -> str:
|
|
| 87 |
return "\n".join(parts).strip()
|
| 88 |
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
def extract_chat_prompt(body: dict[str, object]) -> str:
|
| 91 |
direct_prompt = str(body.get("prompt") or "").strip()
|
| 92 |
if direct_prompt:
|
|
|
|
| 87 |
return "\n".join(parts).strip()
|
| 88 |
|
| 89 |
|
| 90 |
+
def extract_image_from_message_content(content: object) -> tuple[bytes, str] | None:
|
| 91 |
+
import base64 as b64
|
| 92 |
+
|
| 93 |
+
if not isinstance(content, list):
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
for item in content:
|
| 97 |
+
if not isinstance(item, dict):
|
| 98 |
+
continue
|
| 99 |
+
item_type = str(item.get("type") or "").strip()
|
| 100 |
+
if item_type == "image_url":
|
| 101 |
+
url_obj = item.get("image_url") or item
|
| 102 |
+
url = str(url_obj.get("url") or "") if isinstance(url_obj, dict) else str(url_obj)
|
| 103 |
+
if url.startswith("data:"):
|
| 104 |
+
header, _, data = url.partition(",")
|
| 105 |
+
mime = header.split(";")[0].removeprefix("data:")
|
| 106 |
+
return b64.b64decode(data), mime or "image/png"
|
| 107 |
+
if item_type == "input_image":
|
| 108 |
+
image_url = str(item.get("image_url") or "")
|
| 109 |
+
if image_url.startswith("data:"):
|
| 110 |
+
header, _, data = image_url.partition(",")
|
| 111 |
+
mime = header.split(";")[0].removeprefix("data:")
|
| 112 |
+
return b64.b64decode(data), mime or "image/png"
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def extract_chat_image(body: dict[str, object]) -> tuple[bytes, str] | None:
|
| 117 |
+
messages = body.get("messages")
|
| 118 |
+
if not isinstance(messages, list):
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
for message in reversed(messages):
|
| 122 |
+
if not isinstance(message, dict):
|
| 123 |
+
continue
|
| 124 |
+
role = str(message.get("role") or "").strip().lower()
|
| 125 |
+
if role != "user":
|
| 126 |
+
continue
|
| 127 |
+
result = extract_image_from_message_content(message.get("content"))
|
| 128 |
+
if result:
|
| 129 |
+
return result
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
def extract_chat_prompt(body: dict[str, object]) -> str:
|
| 134 |
direct_prompt = str(body.get("prompt") or "").strip()
|
| 135 |
if direct_prompt:
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
web/src/app/image/components/image-composer.tsx
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import Image from "next/image";
|
| 4 |
+
import { ArrowUp, ImagePlus, LoaderCircle, X } from "lucide-react";
|
| 5 |
+
import type { RefObject } from "react";
|
| 6 |
+
|
| 7 |
+
import { Button } from "@/components/ui/button";
|
| 8 |
+
import { Input } from "@/components/ui/input";
|
| 9 |
+
import {
|
| 10 |
+
Select,
|
| 11 |
+
SelectContent,
|
| 12 |
+
SelectItem,
|
| 13 |
+
SelectTrigger,
|
| 14 |
+
SelectValue,
|
| 15 |
+
} from "@/components/ui/select";
|
| 16 |
+
import { Textarea } from "@/components/ui/textarea";
|
| 17 |
+
import type { ImageModel } from "@/lib/api";
|
| 18 |
+
import type { ImageConversationMode } from "@/store/image-conversations";
|
| 19 |
+
import { cn } from "@/lib/utils";
|
| 20 |
+
|
| 21 |
+
type ImageComposerProps = {
|
| 22 |
+
mode: ImageConversationMode;
|
| 23 |
+
prompt: string;
|
| 24 |
+
model: ImageModel;
|
| 25 |
+
imageCount: string;
|
| 26 |
+
availableQuota: string;
|
| 27 |
+
hasAnyGenerating: boolean;
|
| 28 |
+
generatingCount: number;
|
| 29 |
+
referenceImageName: string | null;
|
| 30 |
+
referenceImagePreview: string | null;
|
| 31 |
+
textareaRef: RefObject<HTMLTextAreaElement | null>;
|
| 32 |
+
fileInputRef: RefObject<HTMLInputElement | null>;
|
| 33 |
+
imageModelOptions: Array<{ label: string; value: ImageModel }>;
|
| 34 |
+
onModeChange: (value: ImageConversationMode) => void;
|
| 35 |
+
onPromptChange: (value: string) => void;
|
| 36 |
+
onModelChange: (value: ImageModel) => void;
|
| 37 |
+
onImageCountChange: (value: string) => void;
|
| 38 |
+
onSubmit: () => void | Promise<void>;
|
| 39 |
+
onPickReferenceImage: () => void;
|
| 40 |
+
onReferenceImageChange: (file: File | null) => void | Promise<void>;
|
| 41 |
+
onClearReferenceImage: () => void;
|
| 42 |
+
};
|
| 43 |
+
|
| 44 |
+
export function ImageComposer({
|
| 45 |
+
mode,
|
| 46 |
+
prompt,
|
| 47 |
+
model,
|
| 48 |
+
imageCount,
|
| 49 |
+
availableQuota,
|
| 50 |
+
hasAnyGenerating,
|
| 51 |
+
generatingCount,
|
| 52 |
+
referenceImageName,
|
| 53 |
+
referenceImagePreview,
|
| 54 |
+
textareaRef,
|
| 55 |
+
fileInputRef,
|
| 56 |
+
imageModelOptions,
|
| 57 |
+
onModeChange,
|
| 58 |
+
onPromptChange,
|
| 59 |
+
onModelChange,
|
| 60 |
+
onImageCountChange,
|
| 61 |
+
onSubmit,
|
| 62 |
+
onPickReferenceImage,
|
| 63 |
+
onReferenceImageChange,
|
| 64 |
+
onClearReferenceImage,
|
| 65 |
+
}: ImageComposerProps) {
|
| 66 |
+
return (
|
| 67 |
+
<div className="shrink-0 flex justify-center">
|
| 68 |
+
<div style={{ width: "min(980px, 100%)" }}>
|
| 69 |
+
{mode === "edit" && (
|
| 70 |
+
<input
|
| 71 |
+
ref={fileInputRef}
|
| 72 |
+
type="file"
|
| 73 |
+
accept="image/*"
|
| 74 |
+
className="hidden"
|
| 75 |
+
onChange={(event) => {
|
| 76 |
+
void onReferenceImageChange(event.target.files?.[0] ?? null);
|
| 77 |
+
}}
|
| 78 |
+
/>
|
| 79 |
+
)}
|
| 80 |
+
|
| 81 |
+
{mode === "edit" && referenceImagePreview ? (
|
| 82 |
+
<div className="mb-3 flex items-center gap-3 rounded-[28px] border border-stone-200/80 bg-white px-4 py-4 shadow-[0_18px_48px_rgba(28,25,23,0.08)]">
|
| 83 |
+
<Image
|
| 84 |
+
src={referenceImagePreview}
|
| 85 |
+
alt={referenceImageName || "参考图预览"}
|
| 86 |
+
width={56}
|
| 87 |
+
height={56}
|
| 88 |
+
unoptimized
|
| 89 |
+
className="size-14 rounded-xl object-cover"
|
| 90 |
+
/>
|
| 91 |
+
<div className="min-w-0 flex-1">
|
| 92 |
+
<div className="truncate text-sm font-medium text-stone-800">{referenceImageName}</div>
|
| 93 |
+
<div className="text-xs text-stone-500">将基于这张图片进行编辑</div>
|
| 94 |
+
</div>
|
| 95 |
+
<button
|
| 96 |
+
type="button"
|
| 97 |
+
onClick={onClearReferenceImage}
|
| 98 |
+
className="inline-flex size-8 items-center justify-center rounded-full text-stone-400 transition hover:bg-stone-100 hover:text-stone-700"
|
| 99 |
+
aria-label="移除参考图"
|
| 100 |
+
>
|
| 101 |
+
<X className="size-4" />
|
| 102 |
+
</button>
|
| 103 |
+
</div>
|
| 104 |
+
) : null}
|
| 105 |
+
|
| 106 |
+
<div className="overflow-hidden rounded-[32px] border border-stone-200/80 bg-white shadow-[0_18px_48px_rgba(28,25,23,0.08)]">
|
| 107 |
+
<div
|
| 108 |
+
className="relative cursor-text"
|
| 109 |
+
onClick={() => {
|
| 110 |
+
textareaRef.current?.focus();
|
| 111 |
+
}}
|
| 112 |
+
>
|
| 113 |
+
<Textarea
|
| 114 |
+
ref={textareaRef}
|
| 115 |
+
value={prompt}
|
| 116 |
+
onChange={(event) => onPromptChange(event.target.value)}
|
| 117 |
+
placeholder={mode === "edit" ? "描述你希望如何修改这张参考图" : "输入你想要生成的画面"}
|
| 118 |
+
onKeyDown={(event) => {
|
| 119 |
+
if (event.key === "Enter" && !event.shiftKey) {
|
| 120 |
+
event.preventDefault();
|
| 121 |
+
void onSubmit();
|
| 122 |
+
}
|
| 123 |
+
}}
|
| 124 |
+
className="min-h-[148px] resize-none rounded-[32px] border-0 bg-transparent px-6 pt-6 pb-20 text-[15px] leading-7 text-stone-900 shadow-none placeholder:text-stone-400 focus-visible:ring-0"
|
| 125 |
+
/>
|
| 126 |
+
|
| 127 |
+
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-white via-white/95 to-transparent px-4 pb-4 pt-6 sm:px-6">
|
| 128 |
+
{mode === "edit" && (
|
| 129 |
+
<div className="mb-3 flex flex-wrap items-center gap-2">
|
| 130 |
+
<Button
|
| 131 |
+
type="button"
|
| 132 |
+
variant="outline"
|
| 133 |
+
className="h-10 rounded-full border-stone-200 bg-white px-4 text-sm font-medium text-stone-700 shadow-none"
|
| 134 |
+
onClick={onPickReferenceImage}
|
| 135 |
+
>
|
| 136 |
+
<ImagePlus className="size-4" />
|
| 137 |
+
{referenceImageName ? "重新上传参考图" : "上传参考图"}
|
| 138 |
+
</Button>
|
| 139 |
+
</div>
|
| 140 |
+
)}
|
| 141 |
+
|
| 142 |
+
<div className="flex items-center justify-between gap-3">
|
| 143 |
+
<div className="flex flex-wrap items-center gap-3">
|
| 144 |
+
<div className="rounded-full bg-stone-100 px-3 py-2 text-xs font-medium text-stone-600">剩余额度 {availableQuota}</div>
|
| 145 |
+
{hasAnyGenerating && (
|
| 146 |
+
<div className="flex items-center gap-1.5 rounded-full bg-amber-50 px-3 py-2 text-xs font-medium text-amber-700">
|
| 147 |
+
<LoaderCircle className="size-3 animate-spin" />
|
| 148 |
+
{generatingCount} 个任务进行中
|
| 149 |
+
</div>
|
| 150 |
+
)}
|
| 151 |
+
<Select value={model} onValueChange={(value) => onModelChange(value as ImageModel)}>
|
| 152 |
+
<SelectTrigger className="h-10 w-[164px] rounded-full border-stone-200 bg-white text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0">
|
| 153 |
+
<SelectValue />
|
| 154 |
+
</SelectTrigger>
|
| 155 |
+
<SelectContent>
|
| 156 |
+
{imageModelOptions.map((item) => (
|
| 157 |
+
<SelectItem key={item.value} value={item.value}>
|
| 158 |
+
{item.label}
|
| 159 |
+
</SelectItem>
|
| 160 |
+
))}
|
| 161 |
+
</SelectContent>
|
| 162 |
+
</Select>
|
| 163 |
+
<div className="flex items-center gap-2 rounded-full border border-stone-200 bg-white px-3 py-1">
|
| 164 |
+
<span className="text-sm font-medium text-stone-700">张数</span>
|
| 165 |
+
<Input
|
| 166 |
+
type="number"
|
| 167 |
+
min="1"
|
| 168 |
+
max="10"
|
| 169 |
+
step="1"
|
| 170 |
+
value={imageCount}
|
| 171 |
+
onChange={(event) => onImageCountChange(event.target.value)}
|
| 172 |
+
className="h-8 w-[64px] border-0 bg-transparent px-0 text-center text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0"
|
| 173 |
+
/>
|
| 174 |
+
</div>
|
| 175 |
+
<div className="flex items-center gap-2">
|
| 176 |
+
<ModeButton active={mode === "generate"} onClick={() => onModeChange("generate")}>
|
| 177 |
+
文生图
|
| 178 |
+
</ModeButton>
|
| 179 |
+
<ModeButton active={mode === "edit"} onClick={() => onModeChange("edit")}>
|
| 180 |
+
编辑图
|
| 181 |
+
</ModeButton>
|
| 182 |
+
</div>
|
| 183 |
+
</div>
|
| 184 |
+
|
| 185 |
+
<button
|
| 186 |
+
type="button"
|
| 187 |
+
onClick={() => void onSubmit()}
|
| 188 |
+
disabled={!prompt.trim() || (mode === "edit" && !referenceImagePreview)}
|
| 189 |
+
className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition hover:bg-stone-800 disabled:cursor-not-allowed disabled:bg-stone-300"
|
| 190 |
+
aria-label={mode === "edit" ? "编辑图片" : "生成图片"}
|
| 191 |
+
>
|
| 192 |
+
<ArrowUp className="size-4" />
|
| 193 |
+
</button>
|
| 194 |
+
</div>
|
| 195 |
+
</div>
|
| 196 |
+
</div>
|
| 197 |
+
</div>
|
| 198 |
+
</div>
|
| 199 |
+
</div>
|
| 200 |
+
);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
function ModeButton({
|
| 204 |
+
active,
|
| 205 |
+
children,
|
| 206 |
+
onClick,
|
| 207 |
+
}: {
|
| 208 |
+
active: boolean;
|
| 209 |
+
children: string;
|
| 210 |
+
onClick: () => void;
|
| 211 |
+
}) {
|
| 212 |
+
return (
|
| 213 |
+
<button
|
| 214 |
+
type="button"
|
| 215 |
+
onClick={onClick}
|
| 216 |
+
className={cn(
|
| 217 |
+
"rounded-full px-4 py-2 text-sm font-medium transition",
|
| 218 |
+
active ? "bg-stone-950 text-white" : "bg-stone-100 text-stone-600 hover:bg-stone-200",
|
| 219 |
+
)}
|
| 220 |
+
>
|
| 221 |
+
{children}
|
| 222 |
+
</button>
|
| 223 |
+
);
|
| 224 |
+
}
|
web/src/app/image/components/image-results.tsx
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import Image from "next/image";
|
| 4 |
+
import { LoaderCircle } from "lucide-react";
|
| 5 |
+
|
| 6 |
+
import type { ImageConversation, StoredImage } from "@/store/image-conversations";
|
| 7 |
+
|
| 8 |
+
type ImageResultsProps = {
|
| 9 |
+
selectedConversation: ImageConversation | null;
|
| 10 |
+
isSelectedGenerating: boolean;
|
| 11 |
+
openLightbox: (imageId: string) => void;
|
| 12 |
+
formatConversationTime: (value: string) => string;
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
export function ImageResults({
|
| 16 |
+
selectedConversation,
|
| 17 |
+
isSelectedGenerating,
|
| 18 |
+
openLightbox,
|
| 19 |
+
formatConversationTime,
|
| 20 |
+
}: ImageResultsProps) {
|
| 21 |
+
if (!selectedConversation) {
|
| 22 |
+
return (
|
| 23 |
+
<div className="flex h-full min-h-[420px] items-center justify-center text-center">
|
| 24 |
+
<div className="w-full max-w-4xl">
|
| 25 |
+
<h1
|
| 26 |
+
className="text-3xl font-semibold tracking-tight text-stone-950 md:text-5xl"
|
| 27 |
+
style={{
|
| 28 |
+
fontFamily: '"Palatino Linotype","Book Antiqua","URW Palladio L","Times New Roman",serif',
|
| 29 |
+
}}
|
| 30 |
+
>
|
| 31 |
+
Turn ideas into images
|
| 32 |
+
</h1>
|
| 33 |
+
<p
|
| 34 |
+
className="mt-4 text-[15px] italic tracking-[0.01em] text-stone-500"
|
| 35 |
+
style={{
|
| 36 |
+
fontFamily: '"Palatino Linotype","Book Antiqua","URW Palladio L","Times New Roman",serif',
|
| 37 |
+
}}
|
| 38 |
+
>
|
| 39 |
+
Describe a scene, a mood, or a character, and let the next image start here.
|
| 40 |
+
</p>
|
| 41 |
+
</div>
|
| 42 |
+
</div>
|
| 43 |
+
);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
return (
|
| 47 |
+
<div className="mx-auto flex w-full max-w-[980px] flex-col gap-5">
|
| 48 |
+
<div className="flex justify-end">
|
| 49 |
+
<div className="flex w-full max-w-[80%] flex-col items-end gap-3 px-1 pt-1">
|
| 50 |
+
{selectedConversation.referenceImage ? (
|
| 51 |
+
<div className="w-full max-w-[240px] overflow-hidden rounded-[20px] border border-stone-200 bg-white shadow-sm">
|
| 52 |
+
<Image
|
| 53 |
+
src={selectedConversation.referenceImage.dataUrl}
|
| 54 |
+
alt="参考图"
|
| 55 |
+
width={480}
|
| 56 |
+
height={480}
|
| 57 |
+
unoptimized
|
| 58 |
+
className="block h-auto w-full"
|
| 59 |
+
/>
|
| 60 |
+
</div>
|
| 61 |
+
) : null}
|
| 62 |
+
<div className="text-right text-[15px] leading-8 text-stone-700">{selectedConversation.prompt}</div>
|
| 63 |
+
</div>
|
| 64 |
+
</div>
|
| 65 |
+
|
| 66 |
+
<div className="flex justify-start">
|
| 67 |
+
<div className="w-full p-1">
|
| 68 |
+
<div className="mb-4 flex flex-wrap items-center gap-2 text-xs text-stone-500">
|
| 69 |
+
<span className="rounded-full bg-stone-100 px-3 py-1">{selectedConversation.mode === "edit" ? "编辑图" : "文生图"}</span>
|
| 70 |
+
<span className="rounded-full bg-stone-100 px-3 py-1">{selectedConversation.model}</span>
|
| 71 |
+
<span className="rounded-full bg-stone-100 px-3 py-1">{selectedConversation.count} 张</span>
|
| 72 |
+
<span className="rounded-full bg-stone-100 px-3 py-1">
|
| 73 |
+
{formatConversationTime(selectedConversation.createdAt)}
|
| 74 |
+
</span>
|
| 75 |
+
{isSelectedGenerating && (
|
| 76 |
+
<span className="rounded-full bg-amber-50 px-3 py-1 text-amber-700">处理中</span>
|
| 77 |
+
)}
|
| 78 |
+
</div>
|
| 79 |
+
|
| 80 |
+
{selectedConversation.status === "error" && selectedConversation.images.length === 0 ? (
|
| 81 |
+
<div className="border-l-2 border-rose-300 bg-rose-50/70 px-4 py-4 text-sm leading-6 text-rose-600">
|
| 82 |
+
{selectedConversation.error || "生成失败"}
|
| 83 |
+
</div>
|
| 84 |
+
) : null}
|
| 85 |
+
|
| 86 |
+
{selectedConversation.images.length > 0 ? (
|
| 87 |
+
<div className="columns-1 gap-4 space-y-4 sm:columns-2 xl:columns-3">
|
| 88 |
+
{selectedConversation.images.map((image, index) => (
|
| 89 |
+
<div key={image.id} className="break-inside-avoid overflow-hidden rounded-[22px]">
|
| 90 |
+
<ImageResultCard image={image} index={index} onOpen={openLightbox} />
|
| 91 |
+
</div>
|
| 92 |
+
))}
|
| 93 |
+
</div>
|
| 94 |
+
) : null}
|
| 95 |
+
|
| 96 |
+
{selectedConversation.status === "error" && selectedConversation.images.length > 0 ? (
|
| 97 |
+
<div className="mt-4 border-l-2 border-amber-300 bg-amber-50/70 px-4 py-3 text-sm leading-6 text-amber-700">
|
| 98 |
+
{selectedConversation.error}
|
| 99 |
+
</div>
|
| 100 |
+
) : null}
|
| 101 |
+
</div>
|
| 102 |
+
</div>
|
| 103 |
+
</div>
|
| 104 |
+
);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
function ImageResultCard({
|
| 108 |
+
image,
|
| 109 |
+
index,
|
| 110 |
+
onOpen,
|
| 111 |
+
}: {
|
| 112 |
+
image: StoredImage;
|
| 113 |
+
index: number;
|
| 114 |
+
onOpen: (imageId: string) => void;
|
| 115 |
+
}) {
|
| 116 |
+
if (image.status === "success" && image.b64_json) {
|
| 117 |
+
return (
|
| 118 |
+
<button type="button" onClick={() => onOpen(image.id)} className="group block w-full cursor-zoom-in">
|
| 119 |
+
<Image
|
| 120 |
+
src={`data:image/png;base64,${image.b64_json}`}
|
| 121 |
+
alt={`Generated result ${index + 1}`}
|
| 122 |
+
width={1024}
|
| 123 |
+
height={1024}
|
| 124 |
+
unoptimized
|
| 125 |
+
className="block h-auto w-full transition duration-200 group-hover:brightness-90"
|
| 126 |
+
/>
|
| 127 |
+
</button>
|
| 128 |
+
);
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
if (image.status === "error") {
|
| 132 |
+
return (
|
| 133 |
+
<div className="flex min-h-[320px] items-center justify-center bg-rose-50 px-6 py-8 text-center text-sm leading-6 text-rose-600">
|
| 134 |
+
{image.error || "生成失败"}
|
| 135 |
+
</div>
|
| 136 |
+
);
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
return (
|
| 140 |
+
<div className="flex min-h-[320px] flex-col items-center justify-center gap-3 bg-stone-100/80 px-6 py-8 text-center text-stone-500">
|
| 141 |
+
<div className="rounded-full bg-white p-3 shadow-sm">
|
| 142 |
+
<LoaderCircle className="size-5 animate-spin" />
|
| 143 |
+
</div>
|
| 144 |
+
<p className="text-sm">正在生成图片...</p>
|
| 145 |
+
</div>
|
| 146 |
+
);
|
| 147 |
+
}
|
web/src/app/image/components/image-sidebar.tsx
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import { LoaderCircle, MessageSquarePlus, Trash2 } from "lucide-react";
|
| 4 |
+
|
| 5 |
+
import { Button } from "@/components/ui/button";
|
| 6 |
+
import { cn } from "@/lib/utils";
|
| 7 |
+
import type { ImageConversation } from "@/store/image-conversations";
|
| 8 |
+
|
| 9 |
+
type ImageSidebarProps = {
|
| 10 |
+
conversations: ImageConversation[];
|
| 11 |
+
isLoadingHistory: boolean;
|
| 12 |
+
generatingIds: Set<string>;
|
| 13 |
+
selectedConversationId: string | null;
|
| 14 |
+
onCreateDraft: () => void;
|
| 15 |
+
onClearHistory: () => void | Promise<void>;
|
| 16 |
+
onSelectConversation: (id: string) => void;
|
| 17 |
+
onDeleteConversation: (id: string) => void | Promise<void>;
|
| 18 |
+
formatConversationTime: (value: string) => string;
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
export function ImageSidebar({
|
| 22 |
+
conversations,
|
| 23 |
+
isLoadingHistory,
|
| 24 |
+
generatingIds,
|
| 25 |
+
selectedConversationId,
|
| 26 |
+
onCreateDraft,
|
| 27 |
+
onClearHistory,
|
| 28 |
+
onSelectConversation,
|
| 29 |
+
onDeleteConversation,
|
| 30 |
+
formatConversationTime,
|
| 31 |
+
}: ImageSidebarProps) {
|
| 32 |
+
return (
|
| 33 |
+
<aside className="min-h-0 border-r border-stone-200/70 pr-3">
|
| 34 |
+
<div className="flex h-full min-h-0 flex-col gap-3 py-2">
|
| 35 |
+
<div className="flex items-center gap-2">
|
| 36 |
+
<Button className="h-10 flex-1 rounded-xl bg-stone-950 text-white hover:bg-stone-800" onClick={onCreateDraft}>
|
| 37 |
+
<MessageSquarePlus className="size-4" />
|
| 38 |
+
新建对话
|
| 39 |
+
</Button>
|
| 40 |
+
<Button
|
| 41 |
+
variant="outline"
|
| 42 |
+
className="h-10 rounded-xl border-stone-200 bg-white/85 px-3 text-stone-600 hover:bg-white"
|
| 43 |
+
onClick={() => void onClearHistory()}
|
| 44 |
+
disabled={conversations.length === 0}
|
| 45 |
+
>
|
| 46 |
+
<Trash2 className="size-4" />
|
| 47 |
+
</Button>
|
| 48 |
+
</div>
|
| 49 |
+
|
| 50 |
+
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto pr-1">
|
| 51 |
+
{isLoadingHistory ? (
|
| 52 |
+
<div className="flex items-center gap-2 px-2 py-3 text-sm text-stone-500">
|
| 53 |
+
<LoaderCircle className="size-4 animate-spin" />
|
| 54 |
+
正在读取会话记录
|
| 55 |
+
</div>
|
| 56 |
+
) : conversations.length === 0 ? (
|
| 57 |
+
<div className="px-2 py-3 text-sm leading-6 text-stone-500">还没有图片记录,输入提示词后会在这里显示。</div>
|
| 58 |
+
) : (
|
| 59 |
+
conversations.map((conversation) => {
|
| 60 |
+
const active = conversation.id === selectedConversationId;
|
| 61 |
+
const generating = generatingIds.has(conversation.id);
|
| 62 |
+
return (
|
| 63 |
+
<div
|
| 64 |
+
key={conversation.id}
|
| 65 |
+
className={cn(
|
| 66 |
+
"group relative w-full border-l-2 px-3 py-3 text-left transition",
|
| 67 |
+
active
|
| 68 |
+
? "border-stone-900 bg-black/[0.03] text-stone-950"
|
| 69 |
+
: "border-transparent text-stone-700 hover:border-stone-300 hover:bg-white/40",
|
| 70 |
+
)}
|
| 71 |
+
>
|
| 72 |
+
<button
|
| 73 |
+
type="button"
|
| 74 |
+
onClick={() => onSelectConversation(conversation.id)}
|
| 75 |
+
className="block w-full pr-8 text-left"
|
| 76 |
+
>
|
| 77 |
+
<div className="flex items-center gap-1.5 truncate text-sm font-semibold">
|
| 78 |
+
{generating && <LoaderCircle className="size-3.5 shrink-0 animate-spin text-stone-400" />}
|
| 79 |
+
<span className="truncate">{conversation.title}</span>
|
| 80 |
+
</div>
|
| 81 |
+
<div className={cn("mt-1 text-xs", active ? "text-stone-500" : "text-stone-400")}>
|
| 82 |
+
{formatConversationTime(conversation.createdAt)}
|
| 83 |
+
</div>
|
| 84 |
+
</button>
|
| 85 |
+
<button
|
| 86 |
+
type="button"
|
| 87 |
+
onClick={() => void onDeleteConversation(conversation.id)}
|
| 88 |
+
className="absolute top-3 right-2 inline-flex size-7 items-center justify-center rounded-md text-stone-400 opacity-0 transition hover:bg-stone-100 hover:text-rose-500 group-hover:opacity-100"
|
| 89 |
+
aria-label="删除会话"
|
| 90 |
+
>
|
| 91 |
+
<Trash2 className="size-4" />
|
| 92 |
+
</button>
|
| 93 |
+
</div>
|
| 94 |
+
);
|
| 95 |
+
})
|
| 96 |
+
)}
|
| 97 |
+
</div>
|
| 98 |
+
</div>
|
| 99 |
+
</aside>
|
| 100 |
+
);
|
| 101 |
+
}
|
web/src/app/image/page.tsx
CHANGED
|
@@ -1,31 +1,23 @@
|
|
| 1 |
"use client";
|
| 2 |
|
| 3 |
-
import Image from "next/image";
|
| 4 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 5 |
-
import { ArrowUp, LoaderCircle, MessageSquarePlus, Trash2 } from "lucide-react";
|
| 6 |
import { toast } from "sonner";
|
| 7 |
|
| 8 |
import { ImageLightbox } from "@/components/image-lightbox";
|
| 9 |
-
import {
|
| 10 |
-
import {
|
| 11 |
-
import {
|
| 12 |
-
|
| 13 |
-
SelectContent,
|
| 14 |
-
SelectItem,
|
| 15 |
-
SelectTrigger,
|
| 16 |
-
SelectValue,
|
| 17 |
-
} from "@/components/ui/select";
|
| 18 |
-
import { Textarea } from "@/components/ui/textarea";
|
| 19 |
-
import { fetchAccounts, generateImage, type Account, type ImageModel } from "@/lib/api";
|
| 20 |
import {
|
| 21 |
clearImageConversations,
|
| 22 |
deleteImageConversation,
|
| 23 |
listImageConversations,
|
| 24 |
saveImageConversation,
|
| 25 |
type ImageConversation,
|
|
|
|
| 26 |
type StoredImage,
|
|
|
|
| 27 |
} from "@/store/image-conversations";
|
| 28 |
-
import { cn } from "@/lib/utils";
|
| 29 |
|
| 30 |
const imageModelOptions: Array<{ label: string; value: ImageModel }> = [
|
| 31 |
{ label: "gpt-image-1", value: "gpt-image-1" },
|
|
@@ -89,11 +81,33 @@ async function normalizeConversationHistory(items: ImageConversation[]) {
|
|
| 89 |
return normalized;
|
| 90 |
}
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
export default function ImagePage() {
|
| 93 |
const didLoadQuotaRef = useRef(false);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
const [imagePrompt, setImagePrompt] = useState("");
|
| 95 |
const [imageCount, setImageCount] = useState("1");
|
|
|
|
| 96 |
const [imageModel, setImageModel] = useState<ImageModel>("gpt-image-1");
|
|
|
|
|
|
|
| 97 |
const [conversations, setConversations] = useState<ImageConversation[]>([]);
|
| 98 |
const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);
|
| 99 |
const [isLoadingHistory, setIsLoadingHistory] = useState(true);
|
|
@@ -101,20 +115,19 @@ export default function ImagePage() {
|
|
| 101 |
const [availableQuota, setAvailableQuota] = useState("加载中");
|
| 102 |
const [lightboxOpen, setLightboxOpen] = useState(false);
|
| 103 |
const [lightboxIndex, setLightboxIndex] = useState(0);
|
| 104 |
-
const resultsViewportRef = useRef<HTMLDivElement>(null);
|
| 105 |
-
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
| 106 |
|
| 107 |
-
const parsedCount = useMemo(() => Math.max(1, Math.min(10, Number(imageCount) || 1)), [imageCount]);
|
| 108 |
const selectedConversation = useMemo(
|
| 109 |
() => conversations.find((item) => item.id === selectedConversationId) ?? null,
|
| 110 |
[conversations, selectedConversationId],
|
| 111 |
);
|
|
|
|
| 112 |
const isSelectedGenerating = selectedConversationId !== null && generatingIds.has(selectedConversationId);
|
| 113 |
const hasAnyGenerating = generatingIds.size > 0;
|
| 114 |
|
| 115 |
const addGeneratingId = useCallback((id: string) => {
|
| 116 |
setGeneratingIds((prev) => new Set(prev).add(id));
|
| 117 |
}, []);
|
|
|
|
| 118 |
const removeGeneratingId = useCallback((id: string) => {
|
| 119 |
setGeneratingIds((prev) => {
|
| 120 |
const next = new Set(prev);
|
|
@@ -236,9 +249,19 @@ export default function ImagePage() {
|
|
| 236 |
}
|
| 237 |
};
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
const handleCreateDraft = () => {
|
| 240 |
setSelectedConversationId(null);
|
| 241 |
-
|
| 242 |
textareaRef.current?.focus();
|
| 243 |
};
|
| 244 |
|
|
@@ -269,6 +292,23 @@ export default function ImagePage() {
|
|
| 269 |
}
|
| 270 |
};
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
const handleGenerateImage = async () => {
|
| 273 |
const prompt = imagePrompt.trim();
|
| 274 |
if (!prompt) {
|
|
@@ -276,20 +316,33 @@ export default function ImagePage() {
|
|
| 276 |
return;
|
| 277 |
}
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
const now = new Date().toISOString();
|
| 280 |
-
const conversationId =
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
const draftConversation: ImageConversation = {
|
| 285 |
id: conversationId,
|
| 286 |
title: buildConversationTitle(prompt),
|
| 287 |
prompt,
|
| 288 |
model: imageModel,
|
|
|
|
|
|
|
| 289 |
count: parsedCount,
|
| 290 |
images: Array.from({ length: parsedCount }, (_, index) => ({
|
| 291 |
id: `${conversationId}-${index}`,
|
| 292 |
-
status: "loading"
|
| 293 |
})),
|
| 294 |
createdAt: now,
|
| 295 |
status: "generating",
|
|
@@ -297,14 +350,17 @@ export default function ImagePage() {
|
|
| 297 |
|
| 298 |
addGeneratingId(conversationId);
|
| 299 |
setSelectedConversationId(conversationId);
|
| 300 |
-
|
| 301 |
|
| 302 |
try {
|
| 303 |
await persistConversation(draftConversation);
|
| 304 |
|
| 305 |
const tasks = Array.from({ length: parsedCount }, async (_, index) => {
|
| 306 |
try {
|
| 307 |
-
const data =
|
|
|
|
|
|
|
|
|
|
| 308 |
const first = data.data?.[0];
|
| 309 |
if (!first?.b64_json) {
|
| 310 |
throw new Error(`第 ${index + 1} 张没有返回图片数据`);
|
|
@@ -363,14 +419,23 @@ export default function ImagePage() {
|
|
| 363 |
if (failedCount > 0) {
|
| 364 |
toast.error(`已完成 ${successCount} 张,另有 ${failedCount} 张未生成成功`);
|
| 365 |
} else {
|
| 366 |
-
toast.success(`已生成 ${successCount} 张图片`);
|
| 367 |
}
|
| 368 |
} catch (error) {
|
| 369 |
-
const message = error instanceof Error ? error.message : "生成图片失败";
|
| 370 |
await persistConversation({
|
| 371 |
...draftConversation,
|
| 372 |
status: "error",
|
| 373 |
error: message,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
});
|
| 375 |
toast.error(message);
|
| 376 |
} finally {
|
|
@@ -381,253 +446,53 @@ export default function ImagePage() {
|
|
| 381 |
return (
|
| 382 |
<>
|
| 383 |
<section className="mx-auto grid h-[calc(100vh-5rem)] min-h-0 w-full max-w-[1380px] grid-cols-1 gap-3 px-3 pb-6 lg:grid-cols-[240px_minmax(0,1fr)]">
|
| 384 |
-
<
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
variant="outline"
|
| 396 |
-
className="h-10 rounded-xl border-stone-200 bg-white/85 px-3 text-stone-600 hover:bg-white"
|
| 397 |
-
onClick={() => void handleClearHistory()}
|
| 398 |
-
disabled={conversations.length === 0}
|
| 399 |
-
>
|
| 400 |
-
<Trash2 className="size-4" />
|
| 401 |
-
</Button>
|
| 402 |
-
</div>
|
| 403 |
-
|
| 404 |
-
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto pr-1">
|
| 405 |
-
{isLoadingHistory ? (
|
| 406 |
-
<div className="flex items-center gap-2 px-2 py-3 text-sm text-stone-500">
|
| 407 |
-
<LoaderCircle className="size-4 animate-spin" />
|
| 408 |
-
正在读取会话记录
|
| 409 |
-
</div>
|
| 410 |
-
) : conversations.length === 0 ? (
|
| 411 |
-
<div className="px-2 py-3 text-sm leading-6 text-stone-500">
|
| 412 |
-
还没有图片记录,输入提示词后会在这里显示。
|
| 413 |
-
</div>
|
| 414 |
-
) : (
|
| 415 |
-
conversations.map((conversation) => {
|
| 416 |
-
const active = conversation.id === selectedConversationId;
|
| 417 |
-
const generating = generatingIds.has(conversation.id);
|
| 418 |
-
return (
|
| 419 |
-
<div
|
| 420 |
-
key={conversation.id}
|
| 421 |
-
className={cn(
|
| 422 |
-
"group relative w-full border-l-2 px-3 py-3 text-left transition",
|
| 423 |
-
active
|
| 424 |
-
? "border-stone-900 bg-black/[0.03] text-stone-950"
|
| 425 |
-
: "border-transparent text-stone-700 hover:border-stone-300 hover:bg-white/40",
|
| 426 |
-
)}
|
| 427 |
-
>
|
| 428 |
-
<button
|
| 429 |
-
type="button"
|
| 430 |
-
onClick={() => setSelectedConversationId(conversation.id)}
|
| 431 |
-
className="block w-full pr-8 text-left"
|
| 432 |
-
>
|
| 433 |
-
<div className="flex items-center gap-1.5 truncate text-sm font-semibold">
|
| 434 |
-
{generating && <LoaderCircle className="size-3.5 shrink-0 animate-spin text-stone-400" />}
|
| 435 |
-
<span className="truncate">{conversation.title}</span>
|
| 436 |
-
</div>
|
| 437 |
-
<div className={cn("mt-1 text-xs", active ? "text-stone-500" : "text-stone-400")}>
|
| 438 |
-
{formatConversationTime(conversation.createdAt)}
|
| 439 |
-
</div>
|
| 440 |
-
</button>
|
| 441 |
-
<button
|
| 442 |
-
type="button"
|
| 443 |
-
onClick={() => void handleDeleteConversation(conversation.id)}
|
| 444 |
-
className="absolute top-3 right-2 inline-flex size-7 items-center justify-center rounded-md text-stone-400 opacity-0 transition hover:bg-stone-100 hover:text-rose-500 group-hover:opacity-100"
|
| 445 |
-
aria-label="删除会话"
|
| 446 |
-
>
|
| 447 |
-
<Trash2 className="size-4" />
|
| 448 |
-
</button>
|
| 449 |
-
</div>
|
| 450 |
-
);
|
| 451 |
-
})
|
| 452 |
-
)}
|
| 453 |
-
</div>
|
| 454 |
-
</div>
|
| 455 |
-
</aside>
|
| 456 |
|
| 457 |
<div className="flex min-h-0 flex-col gap-4">
|
| 458 |
<div
|
| 459 |
ref={resultsViewportRef}
|
| 460 |
className="hide-scrollbar min-h-0 flex-1 overflow-y-auto px-2 py-3 sm:px-4 sm:py-4"
|
| 461 |
>
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
fontFamily: '"Palatino Linotype","Book Antiqua","URW Palladio L","Times New Roman",serif',
|
| 469 |
-
}}
|
| 470 |
-
>
|
| 471 |
-
Turn ideas into images
|
| 472 |
-
|
| 473 |
-
</h1>
|
| 474 |
-
<p
|
| 475 |
-
className="mt-4 text-[15px] italic tracking-[0.01em] text-stone-500"
|
| 476 |
-
style={{
|
| 477 |
-
fontFamily: '"Palatino Linotype","Book Antiqua","URW Palladio L","Times New Roman",serif',
|
| 478 |
-
}}
|
| 479 |
-
>
|
| 480 |
-
Describe a scene, a mood, or a character, and let the next image start here.
|
| 481 |
-
</p>
|
| 482 |
-
</div>
|
| 483 |
-
</div>
|
| 484 |
-
) : (
|
| 485 |
-
<div className="mx-auto flex w-full max-w-[980px] flex-col gap-5">
|
| 486 |
-
<div className="flex justify-end">
|
| 487 |
-
<div className="max-w-[80%] px-1 pt-1 text-right text-[15px] leading-8 text-stone-700">
|
| 488 |
-
{selectedConversation.prompt}
|
| 489 |
-
</div>
|
| 490 |
-
</div>
|
| 491 |
-
|
| 492 |
-
<div className="flex justify-start">
|
| 493 |
-
<div className="w-full p-1">
|
| 494 |
-
<div className="mb-4 flex flex-wrap items-center gap-2 text-xs text-stone-500">
|
| 495 |
-
<span className="rounded-full bg-stone-100 px-3 py-1">{selectedConversation.model}</span>
|
| 496 |
-
<span className="rounded-full bg-stone-100 px-3 py-1">{selectedConversation.count} 张</span>
|
| 497 |
-
<span className="rounded-full bg-stone-100 px-3 py-1">
|
| 498 |
-
{formatConversationTime(selectedConversation.createdAt)}
|
| 499 |
-
</span>
|
| 500 |
-
</div>
|
| 501 |
-
|
| 502 |
-
{selectedConversation.status === "error" && selectedConversation.images.length === 0 ? (
|
| 503 |
-
<div className="border-l-2 border-rose-300 bg-rose-50/70 px-4 py-4 text-sm leading-6 text-rose-600">
|
| 504 |
-
{selectedConversation.error || "生成失败"}
|
| 505 |
-
</div>
|
| 506 |
-
) : null}
|
| 507 |
-
|
| 508 |
-
{selectedConversation.images.length > 0 ? (
|
| 509 |
-
<div className="columns-1 gap-4 space-y-4 sm:columns-2 xl:columns-3">
|
| 510 |
-
{selectedConversation.images.map((image, index) => (
|
| 511 |
-
<div key={image.id} className="break-inside-avoid overflow-hidden rounded-[22px]">
|
| 512 |
-
{image.status === "success" && image.b64_json ? (
|
| 513 |
-
<button
|
| 514 |
-
type="button"
|
| 515 |
-
onClick={() => openLightbox(image.id)}
|
| 516 |
-
className="group block w-full cursor-zoom-in"
|
| 517 |
-
>
|
| 518 |
-
<Image
|
| 519 |
-
src={`data:image/png;base64,${image.b64_json}`}
|
| 520 |
-
alt={`Generated result ${index + 1}`}
|
| 521 |
-
width={1024}
|
| 522 |
-
height={1024}
|
| 523 |
-
unoptimized
|
| 524 |
-
className="block h-auto w-full transition duration-200 group-hover:brightness-90"
|
| 525 |
-
/>
|
| 526 |
-
</button>
|
| 527 |
-
) : image.status === "error" ? (
|
| 528 |
-
<div className="flex min-h-[320px] items-center justify-center bg-rose-50 px-6 py-8 text-center text-sm leading-6 text-rose-600">
|
| 529 |
-
{image.error || "生成失败"}
|
| 530 |
-
</div>
|
| 531 |
-
) : (
|
| 532 |
-
<div className="flex min-h-[320px] flex-col items-center justify-center gap-3 bg-stone-100/80 px-6 py-8 text-center text-stone-500">
|
| 533 |
-
<div className="rounded-full bg-white p-3 shadow-sm">
|
| 534 |
-
<LoaderCircle className="size-5 animate-spin" />
|
| 535 |
-
</div>
|
| 536 |
-
<p className="text-sm">正在生成图片...</p>
|
| 537 |
-
</div>
|
| 538 |
-
)}
|
| 539 |
-
</div>
|
| 540 |
-
))}
|
| 541 |
-
</div>
|
| 542 |
-
) : null}
|
| 543 |
-
|
| 544 |
-
{selectedConversation.status === "error" && selectedConversation.images.length > 0 ? (
|
| 545 |
-
<div className="mt-4 border-l-2 border-amber-300 bg-amber-50/70 px-4 py-3 text-sm leading-6 text-amber-700">
|
| 546 |
-
{selectedConversation.error}
|
| 547 |
-
</div>
|
| 548 |
-
) : null}
|
| 549 |
-
</div>
|
| 550 |
-
</div>
|
| 551 |
-
</div>
|
| 552 |
-
)}
|
| 553 |
</div>
|
| 554 |
|
| 555 |
-
<
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
className="min-h-[148px] resize-none rounded-[32px] border-0 bg-transparent px-6 pt-6 pb-20 text-[15px] leading-7 text-stone-900 shadow-none placeholder:text-stone-400 focus-visible:ring-0"
|
| 578 |
-
/>
|
| 579 |
-
|
| 580 |
-
<div className="absolute inset-x-0 bottom-0 flex items-center justify-between bg-gradient-to-t from-white via-white/95 to-transparent px-4 pb-4 pt-10 sm:px-6">
|
| 581 |
-
<div className="flex items-center gap-3">
|
| 582 |
-
<div className="rounded-full bg-stone-100 px-3 py-2 text-xs font-medium text-stone-600">
|
| 583 |
-
剩余额度 {availableQuota}
|
| 584 |
-
</div>
|
| 585 |
-
{hasAnyGenerating && (
|
| 586 |
-
<div className="flex items-center gap-1.5 rounded-full bg-amber-50 px-3 py-2 text-xs font-medium text-amber-700">
|
| 587 |
-
<LoaderCircle className="size-3 animate-spin" />
|
| 588 |
-
{generatingIds.size} 个任���进行中
|
| 589 |
-
</div>
|
| 590 |
-
)}
|
| 591 |
-
<Select value={imageModel} onValueChange={(value) => setImageModel(value as ImageModel)}>
|
| 592 |
-
<SelectTrigger className="h-10 w-[164px] rounded-full border-stone-200 bg-white text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0">
|
| 593 |
-
<SelectValue />
|
| 594 |
-
</SelectTrigger>
|
| 595 |
-
<SelectContent>
|
| 596 |
-
{imageModelOptions.map((item) => (
|
| 597 |
-
<SelectItem key={item.value} value={item.value}>
|
| 598 |
-
{item.label}
|
| 599 |
-
</SelectItem>
|
| 600 |
-
))}
|
| 601 |
-
</SelectContent>
|
| 602 |
-
</Select>
|
| 603 |
-
|
| 604 |
-
<div className="flex items-center gap-2 rounded-full border border-stone-200 bg-white px-3 py-1">
|
| 605 |
-
<span className="text-sm font-medium text-stone-700">张数</span>
|
| 606 |
-
<Input
|
| 607 |
-
type="number"
|
| 608 |
-
min="1"
|
| 609 |
-
max="10"
|
| 610 |
-
step="1"
|
| 611 |
-
value={imageCount}
|
| 612 |
-
onChange={(event) => setImageCount(event.target.value)}
|
| 613 |
-
className="h-8 w-[64px] border-0 bg-transparent px-0 text-center text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0"
|
| 614 |
-
/>
|
| 615 |
-
</div>
|
| 616 |
-
</div>
|
| 617 |
-
|
| 618 |
-
<button
|
| 619 |
-
type="button"
|
| 620 |
-
onClick={() => void handleGenerateImage()}
|
| 621 |
-
disabled={!imagePrompt.trim()}
|
| 622 |
-
className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition hover:bg-stone-800 disabled:cursor-not-allowed disabled:bg-stone-300"
|
| 623 |
-
aria-label="生成图片"
|
| 624 |
-
>
|
| 625 |
-
<ArrowUp className="size-4" />
|
| 626 |
-
</button>
|
| 627 |
-
</div>
|
| 628 |
-
</div>
|
| 629 |
-
</div>
|
| 630 |
-
</div>
|
| 631 |
</div>
|
| 632 |
</section>
|
| 633 |
|
|
|
|
| 1 |
"use client";
|
| 2 |
|
|
|
|
| 3 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
|
|
| 4 |
import { toast } from "sonner";
|
| 5 |
|
| 6 |
import { ImageLightbox } from "@/components/image-lightbox";
|
| 7 |
+
import { editImage, fetchAccounts, generateImage, type Account, type ImageModel } from "@/lib/api";
|
| 8 |
+
import { ImageComposer } from "@/app/image/components/image-composer";
|
| 9 |
+
import { ImageResults } from "@/app/image/components/image-results";
|
| 10 |
+
import { ImageSidebar } from "@/app/image/components/image-sidebar";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
import {
|
| 12 |
clearImageConversations,
|
| 13 |
deleteImageConversation,
|
| 14 |
listImageConversations,
|
| 15 |
saveImageConversation,
|
| 16 |
type ImageConversation,
|
| 17 |
+
type ImageConversationMode,
|
| 18 |
type StoredImage,
|
| 19 |
+
type StoredReferenceImage,
|
| 20 |
} from "@/store/image-conversations";
|
|
|
|
| 21 |
|
| 22 |
const imageModelOptions: Array<{ label: string; value: ImageModel }> = [
|
| 23 |
{ label: "gpt-image-1", value: "gpt-image-1" },
|
|
|
|
| 81 |
return normalized;
|
| 82 |
}
|
| 83 |
|
| 84 |
+
function createId() {
|
| 85 |
+
return typeof crypto !== "undefined" && "randomUUID" in crypto
|
| 86 |
+
? crypto.randomUUID()
|
| 87 |
+
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
function readFileAsDataUrl(file: File) {
|
| 91 |
+
return new Promise<string>((resolve, reject) => {
|
| 92 |
+
const reader = new FileReader();
|
| 93 |
+
reader.onload = () => resolve(String(reader.result || ""));
|
| 94 |
+
reader.onerror = () => reject(new Error("读取参考图失败"));
|
| 95 |
+
reader.readAsDataURL(file);
|
| 96 |
+
});
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
export default function ImagePage() {
|
| 100 |
const didLoadQuotaRef = useRef(false);
|
| 101 |
+
const resultsViewportRef = useRef<HTMLDivElement>(null);
|
| 102 |
+
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
| 103 |
+
const fileInputRef = useRef<HTMLInputElement>(null);
|
| 104 |
+
|
| 105 |
const [imagePrompt, setImagePrompt] = useState("");
|
| 106 |
const [imageCount, setImageCount] = useState("1");
|
| 107 |
+
const [imageMode, setImageMode] = useState<ImageConversationMode>("generate");
|
| 108 |
const [imageModel, setImageModel] = useState<ImageModel>("gpt-image-1");
|
| 109 |
+
const [referenceImageFile, setReferenceImageFile] = useState<File | null>(null);
|
| 110 |
+
const [referenceImagePreview, setReferenceImagePreview] = useState<string | null>(null);
|
| 111 |
const [conversations, setConversations] = useState<ImageConversation[]>([]);
|
| 112 |
const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);
|
| 113 |
const [isLoadingHistory, setIsLoadingHistory] = useState(true);
|
|
|
|
| 115 |
const [availableQuota, setAvailableQuota] = useState("加载中");
|
| 116 |
const [lightboxOpen, setLightboxOpen] = useState(false);
|
| 117 |
const [lightboxIndex, setLightboxIndex] = useState(0);
|
|
|
|
|
|
|
| 118 |
|
|
|
|
| 119 |
const selectedConversation = useMemo(
|
| 120 |
() => conversations.find((item) => item.id === selectedConversationId) ?? null,
|
| 121 |
[conversations, selectedConversationId],
|
| 122 |
);
|
| 123 |
+
const parsedCount = useMemo(() => Math.max(1, Math.min(10, Number(imageCount) || 1)), [imageCount]);
|
| 124 |
const isSelectedGenerating = selectedConversationId !== null && generatingIds.has(selectedConversationId);
|
| 125 |
const hasAnyGenerating = generatingIds.size > 0;
|
| 126 |
|
| 127 |
const addGeneratingId = useCallback((id: string) => {
|
| 128 |
setGeneratingIds((prev) => new Set(prev).add(id));
|
| 129 |
}, []);
|
| 130 |
+
|
| 131 |
const removeGeneratingId = useCallback((id: string) => {
|
| 132 |
setGeneratingIds((prev) => {
|
| 133 |
const next = new Set(prev);
|
|
|
|
| 249 |
}
|
| 250 |
};
|
| 251 |
|
| 252 |
+
const resetComposer = useCallback(() => {
|
| 253 |
+
setImagePrompt("");
|
| 254 |
+
setImageCount("1");
|
| 255 |
+
setReferenceImageFile(null);
|
| 256 |
+
setReferenceImagePreview(null);
|
| 257 |
+
if (fileInputRef.current) {
|
| 258 |
+
fileInputRef.current.value = "";
|
| 259 |
+
}
|
| 260 |
+
}, []);
|
| 261 |
+
|
| 262 |
const handleCreateDraft = () => {
|
| 263 |
setSelectedConversationId(null);
|
| 264 |
+
resetComposer();
|
| 265 |
textareaRef.current?.focus();
|
| 266 |
};
|
| 267 |
|
|
|
|
| 292 |
}
|
| 293 |
};
|
| 294 |
|
| 295 |
+
const handleReferenceImageChange = useCallback(async (file: File | null) => {
|
| 296 |
+
if (!file) {
|
| 297 |
+
setReferenceImageFile(null);
|
| 298 |
+
setReferenceImagePreview(null);
|
| 299 |
+
return;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
try {
|
| 303 |
+
const preview = await readFileAsDataUrl(file);
|
| 304 |
+
setReferenceImageFile(file);
|
| 305 |
+
setReferenceImagePreview(preview);
|
| 306 |
+
} catch (error) {
|
| 307 |
+
const message = error instanceof Error ? error.message : "读取参考图失败";
|
| 308 |
+
toast.error(message);
|
| 309 |
+
}
|
| 310 |
+
}, []);
|
| 311 |
+
|
| 312 |
const handleGenerateImage = async () => {
|
| 313 |
const prompt = imagePrompt.trim();
|
| 314 |
if (!prompt) {
|
|
|
|
| 316 |
return;
|
| 317 |
}
|
| 318 |
|
| 319 |
+
if (imageMode === "edit" && !referenceImageFile) {
|
| 320 |
+
toast.error("请先上传参考图");
|
| 321 |
+
return;
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
const now = new Date().toISOString();
|
| 325 |
+
const conversationId = createId();
|
| 326 |
+
const referenceImage: StoredReferenceImage | undefined =
|
| 327 |
+
imageMode === "edit" && referenceImageFile && referenceImagePreview
|
| 328 |
+
? {
|
| 329 |
+
name: referenceImageFile.name,
|
| 330 |
+
type: referenceImageFile.type || "image/png",
|
| 331 |
+
dataUrl: referenceImagePreview,
|
| 332 |
+
}
|
| 333 |
+
: undefined;
|
| 334 |
+
|
| 335 |
const draftConversation: ImageConversation = {
|
| 336 |
id: conversationId,
|
| 337 |
title: buildConversationTitle(prompt),
|
| 338 |
prompt,
|
| 339 |
model: imageModel,
|
| 340 |
+
mode: imageMode,
|
| 341 |
+
referenceImage,
|
| 342 |
count: parsedCount,
|
| 343 |
images: Array.from({ length: parsedCount }, (_, index) => ({
|
| 344 |
id: `${conversationId}-${index}`,
|
| 345 |
+
status: "loading",
|
| 346 |
})),
|
| 347 |
createdAt: now,
|
| 348 |
status: "generating",
|
|
|
|
| 350 |
|
| 351 |
addGeneratingId(conversationId);
|
| 352 |
setSelectedConversationId(conversationId);
|
| 353 |
+
resetComposer();
|
| 354 |
|
| 355 |
try {
|
| 356 |
await persistConversation(draftConversation);
|
| 357 |
|
| 358 |
const tasks = Array.from({ length: parsedCount }, async (_, index) => {
|
| 359 |
try {
|
| 360 |
+
const data =
|
| 361 |
+
imageMode === "edit" && referenceImageFile
|
| 362 |
+
? await editImage(referenceImageFile, prompt, imageModel)
|
| 363 |
+
: await generateImage(prompt, imageModel);
|
| 364 |
const first = data.data?.[0];
|
| 365 |
if (!first?.b64_json) {
|
| 366 |
throw new Error(`第 ${index + 1} 张没有返回图片数据`);
|
|
|
|
| 419 |
if (failedCount > 0) {
|
| 420 |
toast.error(`已完成 ${successCount} 张,另有 ${failedCount} 张未生成成功`);
|
| 421 |
} else {
|
| 422 |
+
toast.success(imageMode === "edit" ? `已完成 ${successCount} 张图片编辑` : `已生成 ${successCount} 张图片`);
|
| 423 |
}
|
| 424 |
} catch (error) {
|
| 425 |
+
const message = error instanceof Error ? error.message : imageMode === "edit" ? "编辑图片失败" : "生成图片失败";
|
| 426 |
await persistConversation({
|
| 427 |
...draftConversation,
|
| 428 |
status: "error",
|
| 429 |
error: message,
|
| 430 |
+
images: draftConversation.images.map((image) =>
|
| 431 |
+
image.status === "loading"
|
| 432 |
+
? {
|
| 433 |
+
...image,
|
| 434 |
+
status: "error",
|
| 435 |
+
error: message,
|
| 436 |
+
}
|
| 437 |
+
: image,
|
| 438 |
+
),
|
| 439 |
});
|
| 440 |
toast.error(message);
|
| 441 |
} finally {
|
|
|
|
| 446 |
return (
|
| 447 |
<>
|
| 448 |
<section className="mx-auto grid h-[calc(100vh-5rem)] min-h-0 w-full max-w-[1380px] grid-cols-1 gap-3 px-3 pb-6 lg:grid-cols-[240px_minmax(0,1fr)]">
|
| 449 |
+
<ImageSidebar
|
| 450 |
+
conversations={conversations}
|
| 451 |
+
isLoadingHistory={isLoadingHistory}
|
| 452 |
+
generatingIds={generatingIds}
|
| 453 |
+
selectedConversationId={selectedConversationId}
|
| 454 |
+
onCreateDraft={handleCreateDraft}
|
| 455 |
+
onClearHistory={handleClearHistory}
|
| 456 |
+
onSelectConversation={setSelectedConversationId}
|
| 457 |
+
onDeleteConversation={handleDeleteConversation}
|
| 458 |
+
formatConversationTime={formatConversationTime}
|
| 459 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
|
| 461 |
<div className="flex min-h-0 flex-col gap-4">
|
| 462 |
<div
|
| 463 |
ref={resultsViewportRef}
|
| 464 |
className="hide-scrollbar min-h-0 flex-1 overflow-y-auto px-2 py-3 sm:px-4 sm:py-4"
|
| 465 |
>
|
| 466 |
+
<ImageResults
|
| 467 |
+
selectedConversation={selectedConversation}
|
| 468 |
+
isSelectedGenerating={isSelectedGenerating}
|
| 469 |
+
openLightbox={openLightbox}
|
| 470 |
+
formatConversationTime={formatConversationTime}
|
| 471 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
</div>
|
| 473 |
|
| 474 |
+
<ImageComposer
|
| 475 |
+
mode={imageMode}
|
| 476 |
+
prompt={imagePrompt}
|
| 477 |
+
model={imageModel}
|
| 478 |
+
imageCount={imageCount}
|
| 479 |
+
availableQuota={availableQuota}
|
| 480 |
+
hasAnyGenerating={hasAnyGenerating}
|
| 481 |
+
generatingCount={generatingIds.size}
|
| 482 |
+
referenceImageName={referenceImageFile?.name ?? null}
|
| 483 |
+
referenceImagePreview={referenceImagePreview}
|
| 484 |
+
textareaRef={textareaRef}
|
| 485 |
+
fileInputRef={fileInputRef}
|
| 486 |
+
imageModelOptions={imageModelOptions}
|
| 487 |
+
onModeChange={setImageMode}
|
| 488 |
+
onPromptChange={setImagePrompt}
|
| 489 |
+
onModelChange={setImageModel}
|
| 490 |
+
onImageCountChange={setImageCount}
|
| 491 |
+
onSubmit={handleGenerateImage}
|
| 492 |
+
onPickReferenceImage={() => fileInputRef.current?.click()}
|
| 493 |
+
onReferenceImageChange={handleReferenceImageChange}
|
| 494 |
+
onClearReferenceImage={() => void handleReferenceImageChange(null)}
|
| 495 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
</div>
|
| 497 |
</section>
|
| 498 |
|
web/src/lib/api.ts
CHANGED
|
@@ -117,6 +117,22 @@ export async function generateImage(prompt: string, model: ImageModel = "gpt-ima
|
|
| 117 |
);
|
| 118 |
}
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
// ── CPA (CLIProxyAPI) ──────────────────────────────────────────────
|
| 121 |
|
| 122 |
export type CPAPool = {
|
|
|
|
| 117 |
);
|
| 118 |
}
|
| 119 |
|
| 120 |
+
export async function editImage(file: File, prompt: string, model: ImageModel = "gpt-image-1") {
|
| 121 |
+
const formData = new FormData();
|
| 122 |
+
formData.append("image", file);
|
| 123 |
+
formData.append("prompt", prompt);
|
| 124 |
+
formData.append("model", model);
|
| 125 |
+
formData.append("n", "1");
|
| 126 |
+
|
| 127 |
+
return httpRequest<{ created: number; data: Array<{ b64_json: string; revised_prompt?: string }> }>(
|
| 128 |
+
"/v1/images/edits",
|
| 129 |
+
{
|
| 130 |
+
method: "POST",
|
| 131 |
+
body: formData,
|
| 132 |
+
},
|
| 133 |
+
);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
// ── CPA (CLIProxyAPI) ──────────────────────────────────────────────
|
| 137 |
|
| 138 |
export type CPAPool = {
|
web/src/store/image-conversations.ts
CHANGED
|
@@ -4,6 +4,14 @@ import localforage from "localforage";
|
|
| 4 |
|
| 5 |
import type { ImageModel } from "@/lib/api";
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
export type StoredImage = {
|
| 8 |
id: string;
|
| 9 |
status?: "loading" | "success" | "error";
|
|
@@ -18,6 +26,8 @@ export type ImageConversation = {
|
|
| 18 |
title: string;
|
| 19 |
prompt: string;
|
| 20 |
model: ImageModel;
|
|
|
|
|
|
|
| 21 |
count: number;
|
| 22 |
images: StoredImage[];
|
| 23 |
createdAt: string;
|
|
@@ -45,6 +55,7 @@ function normalizeStoredImage(image: StoredImage): StoredImage {
|
|
| 45 |
function normalizeConversation(conversation: ImageConversation): ImageConversation {
|
| 46 |
return {
|
| 47 |
...conversation,
|
|
|
|
| 48 |
images: (conversation.images || []).map(normalizeStoredImage),
|
| 49 |
};
|
| 50 |
}
|
|
|
|
| 4 |
|
| 5 |
import type { ImageModel } from "@/lib/api";
|
| 6 |
|
| 7 |
+
export type ImageConversationMode = "generate" | "edit";
|
| 8 |
+
|
| 9 |
+
export type StoredReferenceImage = {
|
| 10 |
+
name: string;
|
| 11 |
+
type: string;
|
| 12 |
+
dataUrl: string;
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
export type StoredImage = {
|
| 16 |
id: string;
|
| 17 |
status?: "loading" | "success" | "error";
|
|
|
|
| 26 |
title: string;
|
| 27 |
prompt: string;
|
| 28 |
model: ImageModel;
|
| 29 |
+
mode?: ImageConversationMode;
|
| 30 |
+
referenceImage?: StoredReferenceImage;
|
| 31 |
count: number;
|
| 32 |
images: StoredImage[];
|
| 33 |
createdAt: string;
|
|
|
|
| 55 |
function normalizeConversation(conversation: ImageConversation): ImageConversation {
|
| 56 |
return {
|
| 57 |
...conversation,
|
| 58 |
+
mode: conversation.mode === "edit" ? "edit" : "generate",
|
| 59 |
images: (conversation.images || []).map(normalizeStoredImage),
|
| 60 |
};
|
| 61 |
}
|