HouYunFei Codex commited on
Commit ·
cc8994b
1
Parent(s): 995894a
support optional image size flow
Browse filesCo-Authored-By: Codex <noreply@openai.com>
- api/ai.py +4 -3
- services/chatgpt_service.py +16 -12
- services/openai_backend_api.py +5 -5
- web/src/app/image/components/image-composer.tsx +65 -28
- web/src/app/image/page.tsx +13 -5
- web/src/components/top-nav.tsx +1 -1
- web/src/lib/api.ts +6 -4
- web/src/store/image-conversations.ts +2 -2
api/ai.py
CHANGED
|
@@ -15,7 +15,7 @@ class ImageGenerationRequest(BaseModel):
|
|
| 15 |
prompt: str = Field(..., min_length=1)
|
| 16 |
model: str = "gpt-image-2"
|
| 17 |
n: int = Field(default=1, ge=1, le=4)
|
| 18 |
-
size: str =
|
| 19 |
response_format: str = "b64_json"
|
| 20 |
history_disabled: bool = True
|
| 21 |
stream: bool | None = None
|
|
@@ -88,6 +88,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
|
|
| 88 |
prompt: str = Form(...),
|
| 89 |
model: str = Form(default="gpt-image-2"),
|
| 90 |
n: int = Form(default=1),
|
|
|
|
| 91 |
response_format: str = Form(default="b64_json"),
|
| 92 |
stream: bool | None = Form(default=None),
|
| 93 |
):
|
|
@@ -108,12 +109,12 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
|
|
| 108 |
if not account_service.has_available_account():
|
| 109 |
raise_image_quota_error(RuntimeError("no available image quota"))
|
| 110 |
return StreamingResponse(
|
| 111 |
-
sse_json_stream(chatgpt_service.stream_image_edit(prompt, images, model, n, response_format, base_url)),
|
| 112 |
media_type="text/event-stream",
|
| 113 |
)
|
| 114 |
try:
|
| 115 |
return await run_in_threadpool(
|
| 116 |
-
chatgpt_service.edit_with_pool, prompt, images, model, n, response_format, base_url
|
| 117 |
)
|
| 118 |
except ImageGenerationError as exc:
|
| 119 |
raise_image_quota_error(exc)
|
|
|
|
| 15 |
prompt: str = Field(..., min_length=1)
|
| 16 |
model: str = "gpt-image-2"
|
| 17 |
n: int = Field(default=1, ge=1, le=4)
|
| 18 |
+
size: str | None = None
|
| 19 |
response_format: str = "b64_json"
|
| 20 |
history_disabled: bool = True
|
| 21 |
stream: bool | None = None
|
|
|
|
| 88 |
prompt: str = Form(...),
|
| 89 |
model: str = Form(default="gpt-image-2"),
|
| 90 |
n: int = Form(default=1),
|
| 91 |
+
size: str | None = Form(default=None),
|
| 92 |
response_format: str = Form(default="b64_json"),
|
| 93 |
stream: bool | None = Form(default=None),
|
| 94 |
):
|
|
|
|
| 109 |
if not account_service.has_available_account():
|
| 110 |
raise_image_quota_error(RuntimeError("no available image quota"))
|
| 111 |
return StreamingResponse(
|
| 112 |
+
sse_json_stream(chatgpt_service.stream_image_edit(prompt, images, model, n, size, response_format, base_url)),
|
| 113 |
media_type="text/event-stream",
|
| 114 |
)
|
| 115 |
try:
|
| 116 |
return await run_in_threadpool(
|
| 117 |
+
chatgpt_service.edit_with_pool, prompt, images, model, n, size, response_format, base_url
|
| 118 |
)
|
| 119 |
except ImageGenerationError as exc:
|
| 120 |
raise_image_quota_error(exc)
|
services/chatgpt_service.py
CHANGED
|
@@ -513,7 +513,7 @@ class ChatGPTService:
|
|
| 513 |
index: int,
|
| 514 |
total: int,
|
| 515 |
request_token: str,
|
| 516 |
-
size: str =
|
| 517 |
response_format: str = "b64_json",
|
| 518 |
base_url: str | None = None,
|
| 519 |
images: list[str] | None = None,
|
|
@@ -568,7 +568,7 @@ class ChatGPTService:
|
|
| 568 |
prompt: str,
|
| 569 |
model: str,
|
| 570 |
n: int,
|
| 571 |
-
size: str =
|
| 572 |
response_format: str = "b64_json",
|
| 573 |
base_url: str | None = None,
|
| 574 |
) -> Iterator[dict[str, object]]:
|
|
@@ -643,7 +643,7 @@ class ChatGPTService:
|
|
| 643 |
if not emitted:
|
| 644 |
raise ImageGenerationError(last_error or "image generation failed")
|
| 645 |
|
| 646 |
-
def generate_with_pool(self, prompt: str, model: str, n: int, size: str =
|
| 647 |
base_url: str = None):
|
| 648 |
created = None
|
| 649 |
image_items: list[dict[str, object]] = []
|
|
@@ -663,7 +663,7 @@ class ChatGPTService:
|
|
| 663 |
prompt: str,
|
| 664 |
model: str,
|
| 665 |
n: int,
|
| 666 |
-
size: str =
|
| 667 |
response_format: str = "b64_json",
|
| 668 |
base_url: str | None = None,
|
| 669 |
) -> Iterator[dict[str, object]]:
|
|
@@ -749,6 +749,7 @@ class ChatGPTService:
|
|
| 749 |
images: Iterable[tuple[bytes, str, str]],
|
| 750 |
model: str,
|
| 751 |
n: int,
|
|
|
|
| 752 |
response_format: str = "b64_json",
|
| 753 |
base_url: str = None,
|
| 754 |
):
|
|
@@ -786,6 +787,7 @@ class ChatGPTService:
|
|
| 786 |
image=self._encode_images(normalized_images),
|
| 787 |
prompt=prompt,
|
| 788 |
model=model,
|
|
|
|
| 789 |
response_format="b64_json",
|
| 790 |
), prompt, response_format, base_url)
|
| 791 |
account = self.account_service.mark_image_result(request_token, success=True)
|
|
@@ -835,6 +837,7 @@ class ChatGPTService:
|
|
| 835 |
images: Iterable[tuple[bytes, str, str]],
|
| 836 |
model: str,
|
| 837 |
n: int,
|
|
|
|
| 838 |
response_format: str = "b64_json",
|
| 839 |
base_url: str | None = None,
|
| 840 |
) -> Iterator[dict[str, object]]:
|
|
@@ -873,14 +876,15 @@ class ChatGPTService:
|
|
| 873 |
has_result = False
|
| 874 |
try:
|
| 875 |
for chunk in self._stream_single_image_result(
|
| 876 |
-
prompt,
|
| 877 |
-
model,
|
| 878 |
-
index,
|
| 879 |
-
n,
|
| 880 |
-
request_token,
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
|
|
|
| 884 |
):
|
| 885 |
emitted = True
|
| 886 |
emitted_for_request = True
|
|
|
|
| 513 |
index: int,
|
| 514 |
total: int,
|
| 515 |
request_token: str,
|
| 516 |
+
size: str | None = None,
|
| 517 |
response_format: str = "b64_json",
|
| 518 |
base_url: str | None = None,
|
| 519 |
images: list[str] | None = None,
|
|
|
|
| 568 |
prompt: str,
|
| 569 |
model: str,
|
| 570 |
n: int,
|
| 571 |
+
size: str | None = None,
|
| 572 |
response_format: str = "b64_json",
|
| 573 |
base_url: str | None = None,
|
| 574 |
) -> Iterator[dict[str, object]]:
|
|
|
|
| 643 |
if not emitted:
|
| 644 |
raise ImageGenerationError(last_error or "image generation failed")
|
| 645 |
|
| 646 |
+
def generate_with_pool(self, prompt: str, model: str, n: int, size: str | None = None, response_format: str = "b64_json",
|
| 647 |
base_url: str = None):
|
| 648 |
created = None
|
| 649 |
image_items: list[dict[str, object]] = []
|
|
|
|
| 663 |
prompt: str,
|
| 664 |
model: str,
|
| 665 |
n: int,
|
| 666 |
+
size: str | None = None,
|
| 667 |
response_format: str = "b64_json",
|
| 668 |
base_url: str | None = None,
|
| 669 |
) -> Iterator[dict[str, object]]:
|
|
|
|
| 749 |
images: Iterable[tuple[bytes, str, str]],
|
| 750 |
model: str,
|
| 751 |
n: int,
|
| 752 |
+
size: str | None = None,
|
| 753 |
response_format: str = "b64_json",
|
| 754 |
base_url: str = None,
|
| 755 |
):
|
|
|
|
| 787 |
image=self._encode_images(normalized_images),
|
| 788 |
prompt=prompt,
|
| 789 |
model=model,
|
| 790 |
+
size=size,
|
| 791 |
response_format="b64_json",
|
| 792 |
), prompt, response_format, base_url)
|
| 793 |
account = self.account_service.mark_image_result(request_token, success=True)
|
|
|
|
| 837 |
images: Iterable[tuple[bytes, str, str]],
|
| 838 |
model: str,
|
| 839 |
n: int,
|
| 840 |
+
size: str | None = None,
|
| 841 |
response_format: str = "b64_json",
|
| 842 |
base_url: str | None = None,
|
| 843 |
) -> Iterator[dict[str, object]]:
|
|
|
|
| 876 |
has_result = False
|
| 877 |
try:
|
| 878 |
for chunk in self._stream_single_image_result(
|
| 879 |
+
prompt=prompt,
|
| 880 |
+
model=model,
|
| 881 |
+
index=index,
|
| 882 |
+
total=n,
|
| 883 |
+
request_token=request_token,
|
| 884 |
+
size=size,
|
| 885 |
+
response_format=response_format,
|
| 886 |
+
base_url=base_url,
|
| 887 |
+
images=encoded_images,
|
| 888 |
):
|
| 889 |
emitted = True
|
| 890 |
emitted_for_request = True
|
services/openai_backend_api.py
CHANGED
|
@@ -293,7 +293,7 @@ class OpenAIBackendAPI:
|
|
| 293 |
data.sort(key=lambda item: item["id"])
|
| 294 |
return {"object": "list", "data": data}
|
| 295 |
|
| 296 |
-
def _build_image_prompt(self, prompt: str, size: str) -> str:
|
| 297 |
"""把标准图片 prompt 和宽高比转成底层图片生成 prompt。"""
|
| 298 |
if not size:
|
| 299 |
return prompt
|
|
@@ -726,7 +726,7 @@ class OpenAIBackendAPI:
|
|
| 726 |
data.append({"url": self._save_image_bytes(response.content)})
|
| 727 |
return {"created": int(time.time()), "data": data}
|
| 728 |
|
| 729 |
-
def _run_image_task(self, prompt: str, model: str, size: str, images: Optional[list[str]] = None,
|
| 730 |
response_format: str = "url") -> Dict[str, Any]:
|
| 731 |
"""执行图片生成或图片编辑主流程。"""
|
| 732 |
if not self.access_token:
|
|
@@ -934,7 +934,7 @@ class OpenAIBackendAPI:
|
|
| 934 |
self,
|
| 935 |
prompt: str,
|
| 936 |
model: str = "gpt-image-2",
|
| 937 |
-
size: str =
|
| 938 |
images: Optional[list[str]] = None,
|
| 939 |
) -> Iterator[Dict[str, Any]]:
|
| 940 |
if not self.access_token:
|
|
@@ -1297,14 +1297,14 @@ class OpenAIBackendAPI:
|
|
| 1297 |
"""返回当前模式下可用模型,格式对齐 OpenAI `/v1/models`。"""
|
| 1298 |
return self._normalize_models(self._get_models_raw(authenticated=bool(self.access_token)))
|
| 1299 |
|
| 1300 |
-
def images_generations(self, prompt: str, model: str = "gpt-image-2", size: str =
|
| 1301 |
response_format: str = "url") -> Dict[str, Any]:
|
| 1302 |
"""返回 OpenAI `/v1/images/generations` 风格结果。"""
|
| 1303 |
if self._is_codex_image_model(model):
|
| 1304 |
return self._run_codex_image_task(prompt, response_format=response_format)
|
| 1305 |
return self._run_image_task(prompt, model, size, response_format=response_format)
|
| 1306 |
|
| 1307 |
-
def images_edits(self, image: str | list[str], prompt: str, model: str = "gpt-image-2", size: str =
|
| 1308 |
response_format: str = "url") -> Dict[str, Any]:
|
| 1309 |
"""返回 OpenAI `/v1/images/edits` 风格结果。"""
|
| 1310 |
images = [image] if isinstance(image, str) else image
|
|
|
|
| 293 |
data.sort(key=lambda item: item["id"])
|
| 294 |
return {"object": "list", "data": data}
|
| 295 |
|
| 296 |
+
def _build_image_prompt(self, prompt: str, size: str | None) -> str:
|
| 297 |
"""把标准图片 prompt 和宽高比转成底层图片生成 prompt。"""
|
| 298 |
if not size:
|
| 299 |
return prompt
|
|
|
|
| 726 |
data.append({"url": self._save_image_bytes(response.content)})
|
| 727 |
return {"created": int(time.time()), "data": data}
|
| 728 |
|
| 729 |
+
def _run_image_task(self, prompt: str, model: str, size: str | None, images: Optional[list[str]] = None,
|
| 730 |
response_format: str = "url") -> Dict[str, Any]:
|
| 731 |
"""执行图片生成或图片编辑主流程。"""
|
| 732 |
if not self.access_token:
|
|
|
|
| 934 |
self,
|
| 935 |
prompt: str,
|
| 936 |
model: str = "gpt-image-2",
|
| 937 |
+
size: str | None = None,
|
| 938 |
images: Optional[list[str]] = None,
|
| 939 |
) -> Iterator[Dict[str, Any]]:
|
| 940 |
if not self.access_token:
|
|
|
|
| 1297 |
"""返回当前模式下可用模型,格式对齐 OpenAI `/v1/models`。"""
|
| 1298 |
return self._normalize_models(self._get_models_raw(authenticated=bool(self.access_token)))
|
| 1299 |
|
| 1300 |
+
def images_generations(self, prompt: str, model: str = "gpt-image-2", size: str | None = None,
|
| 1301 |
response_format: str = "url") -> Dict[str, Any]:
|
| 1302 |
"""返回 OpenAI `/v1/images/generations` 风格结果。"""
|
| 1303 |
if self._is_codex_image_model(model):
|
| 1304 |
return self._run_codex_image_task(prompt, response_format=response_format)
|
| 1305 |
return self._run_image_task(prompt, model, size, response_format=response_format)
|
| 1306 |
|
| 1307 |
+
def images_edits(self, image: str | list[str], prompt: str, model: str = "gpt-image-2", size: str | None = None,
|
| 1308 |
response_format: str = "url") -> Dict[str, Any]:
|
| 1309 |
"""返回 OpenAI `/v1/images/edits` 风格结果。"""
|
| 1310 |
images = [image] if isinstance(image, str) else image
|
web/src/app/image/components/image-composer.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"use client";
|
| 2 |
-
import { ArrowUp, ImagePlus, LoaderCircle, X } from "lucide-react";
|
| 3 |
-
import { useMemo, useState, type ClipboardEvent, type RefObject } from "react";
|
| 4 |
|
| 5 |
import { ImageLightbox } from "@/components/image-lightbox";
|
| 6 |
import { Button } from "@/components/ui/button";
|
|
@@ -8,13 +8,6 @@ import { Input } from "@/components/ui/input";
|
|
| 8 |
import { Textarea } from "@/components/ui/textarea";
|
| 9 |
import type { ImageConversationMode } from "@/store/image-conversations";
|
| 10 |
import { cn } from "@/lib/utils";
|
| 11 |
-
import {
|
| 12 |
-
Select,
|
| 13 |
-
SelectContent,
|
| 14 |
-
SelectItem,
|
| 15 |
-
SelectTrigger,
|
| 16 |
-
SelectValue,
|
| 17 |
-
} from "@/components/ui/select";
|
| 18 |
|
| 19 |
type ImageComposerProps = {
|
| 20 |
mode: ImageConversationMode;
|
|
@@ -57,10 +50,36 @@ export function ImageComposer({
|
|
| 57 |
}: ImageComposerProps) {
|
| 58 |
const [lightboxOpen, setLightboxOpen] = useState(false);
|
| 59 |
const [lightboxIndex, setLightboxIndex] = useState(0);
|
|
|
|
|
|
|
| 60 |
const lightboxImages = useMemo(
|
| 61 |
() => referenceImages.map((image, index) => ({ id: `${image.name}-${index}`, src: image.dataUrl })),
|
| 62 |
[referenceImages],
|
| 63 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
const handleTextareaPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
|
| 66 |
const imageFiles = Array.from(event.clipboardData.files).filter((file) => file.type.startsWith("image/"));
|
|
@@ -123,7 +142,7 @@ export function ImageComposer({
|
|
| 123 |
</div>
|
| 124 |
) : null}
|
| 125 |
|
| 126 |
-
<div className="
|
| 127 |
<div
|
| 128 |
className="relative cursor-text"
|
| 129 |
onClick={() => {
|
|
@@ -190,25 +209,43 @@ export function ImageComposer({
|
|
| 190 |
className="h-7 w-[40px] border-0 bg-transparent px-0 text-center text-xs font-medium text-stone-700 shadow-none focus-visible:ring-0 sm:h-8 sm:w-[64px] sm:text-sm"
|
| 191 |
/>
|
| 192 |
</div>
|
| 193 |
-
<div
|
|
|
|
|
|
|
|
|
|
| 194 |
<span className="font-medium text-stone-700 sm:text-sm">比例</span>
|
| 195 |
-
<
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
<
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
</div>
|
| 213 |
|
| 214 |
<div className="flex items-center gap-1.5 sm:gap-2">
|
|
|
|
| 1 |
"use client";
|
| 2 |
+
import { ArrowUp, Check, ChevronDown, ImagePlus, LoaderCircle, X } from "lucide-react";
|
| 3 |
+
import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type RefObject } from "react";
|
| 4 |
|
| 5 |
import { ImageLightbox } from "@/components/image-lightbox";
|
| 6 |
import { Button } from "@/components/ui/button";
|
|
|
|
| 8 |
import { Textarea } from "@/components/ui/textarea";
|
| 9 |
import type { ImageConversationMode } from "@/store/image-conversations";
|
| 10 |
import { cn } from "@/lib/utils";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
type ImageComposerProps = {
|
| 13 |
mode: ImageConversationMode;
|
|
|
|
| 50 |
}: ImageComposerProps) {
|
| 51 |
const [lightboxOpen, setLightboxOpen] = useState(false);
|
| 52 |
const [lightboxIndex, setLightboxIndex] = useState(0);
|
| 53 |
+
const [isSizeMenuOpen, setIsSizeMenuOpen] = useState(false);
|
| 54 |
+
const sizeMenuRef = useRef<HTMLDivElement>(null);
|
| 55 |
const lightboxImages = useMemo(
|
| 56 |
() => referenceImages.map((image, index) => ({ id: `${image.name}-${index}`, src: image.dataUrl })),
|
| 57 |
[referenceImages],
|
| 58 |
);
|
| 59 |
+
const imageSizeOptions = [
|
| 60 |
+
{ value: "", label: "未指定" },
|
| 61 |
+
{ value: "1:1", label: "1:1 (正方形)" },
|
| 62 |
+
{ value: "16:9", label: "16:9 (横版)" },
|
| 63 |
+
{ value: "4:3", label: "4:3 (横版)" },
|
| 64 |
+
{ value: "3:4", label: "3:4 (竖版)" },
|
| 65 |
+
{ value: "9:16", label: "9:16 (竖版)" },
|
| 66 |
+
];
|
| 67 |
+
const imageSizeLabel = imageSizeOptions.find((option) => option.value === imageSize)?.label || "未指定";
|
| 68 |
+
|
| 69 |
+
useEffect(() => {
|
| 70 |
+
if (!isSizeMenuOpen) {
|
| 71 |
+
return;
|
| 72 |
+
}
|
| 73 |
+
const handlePointerDown = (event: MouseEvent) => {
|
| 74 |
+
if (!sizeMenuRef.current?.contains(event.target as Node)) {
|
| 75 |
+
setIsSizeMenuOpen(false);
|
| 76 |
+
}
|
| 77 |
+
};
|
| 78 |
+
window.addEventListener("mousedown", handlePointerDown);
|
| 79 |
+
return () => {
|
| 80 |
+
window.removeEventListener("mousedown", handlePointerDown);
|
| 81 |
+
};
|
| 82 |
+
}, [isSizeMenuOpen]);
|
| 83 |
|
| 84 |
const handleTextareaPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
|
| 85 |
const imageFiles = Array.from(event.clipboardData.files).filter((file) => file.type.startsWith("image/"));
|
|
|
|
| 142 |
</div>
|
| 143 |
) : null}
|
| 144 |
|
| 145 |
+
<div className="rounded-[32px] border border-stone-200 bg-white">
|
| 146 |
<div
|
| 147 |
className="relative cursor-text"
|
| 148 |
onClick={() => {
|
|
|
|
| 209 |
className="h-7 w-[40px] border-0 bg-transparent px-0 text-center text-xs font-medium text-stone-700 shadow-none focus-visible:ring-0 sm:h-8 sm:w-[64px] sm:text-sm"
|
| 210 |
/>
|
| 211 |
</div>
|
| 212 |
+
<div
|
| 213 |
+
ref={sizeMenuRef}
|
| 214 |
+
className="relative flex items-center gap-1.5 rounded-full border border-stone-200 bg-white px-2 py-0.5 text-[11px] sm:gap-2 sm:px-3 sm:py-1 sm:text-[13px]"
|
| 215 |
+
>
|
| 216 |
<span className="font-medium text-stone-700 sm:text-sm">比例</span>
|
| 217 |
+
<button
|
| 218 |
+
type="button"
|
| 219 |
+
className="flex h-7 w-[110px] items-center justify-between bg-transparent text-left text-xs font-bold text-stone-700 sm:h-8 sm:w-[132px]"
|
| 220 |
+
onClick={() => setIsSizeMenuOpen((open) => !open)}
|
| 221 |
+
>
|
| 222 |
+
<span className="truncate">{imageSizeLabel}</span>
|
| 223 |
+
<ChevronDown className={cn("size-4 shrink-0 opacity-60 transition", isSizeMenuOpen && "rotate-180")} />
|
| 224 |
+
</button>
|
| 225 |
+
{isSizeMenuOpen ? (
|
| 226 |
+
<div className="absolute bottom-[calc(100%+10px)] left-0 z-50 w-[170px] overflow-hidden rounded-3xl border border-white/80 bg-white p-2 shadow-[0_24px_80px_-32px_rgba(15,23,42,0.35)] sm:w-[186px]">
|
| 227 |
+
{imageSizeOptions.map((option) => {
|
| 228 |
+
const active = option.value === imageSize;
|
| 229 |
+
return (
|
| 230 |
+
<button
|
| 231 |
+
key={option.label}
|
| 232 |
+
type="button"
|
| 233 |
+
className={cn(
|
| 234 |
+
"flex w-full items-center justify-between rounded-2xl px-3 py-2 text-left text-sm text-stone-700 transition hover:bg-stone-100",
|
| 235 |
+
active && "bg-stone-100 font-medium text-stone-950",
|
| 236 |
+
)}
|
| 237 |
+
onClick={() => {
|
| 238 |
+
onImageSizeChange(option.value);
|
| 239 |
+
setIsSizeMenuOpen(false);
|
| 240 |
+
}}
|
| 241 |
+
>
|
| 242 |
+
<span>{option.label}</span>
|
| 243 |
+
{active ? <Check className="size-4" /> : null}
|
| 244 |
+
</button>
|
| 245 |
+
);
|
| 246 |
+
})}
|
| 247 |
+
</div>
|
| 248 |
+
) : null}
|
| 249 |
</div>
|
| 250 |
|
| 251 |
<div className="flex items-center gap-1.5 sm:gap-2">
|
web/src/app/image/page.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"use client";
|
| 2 |
|
| 3 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 4 |
-
import { History, Plus } from "lucide-react";
|
| 5 |
import { toast } from "sonner";
|
| 6 |
|
| 7 |
import { ImageComposer } from "@/app/image/components/image-composer";
|
|
@@ -180,7 +180,7 @@ export default function ImagePage() {
|
|
| 180 |
const [imagePrompt, setImagePrompt] = useState("");
|
| 181 |
const [imageCount, setImageCount] = useState("1");
|
| 182 |
const [imageMode, setImageMode] = useState<ImageConversationMode>("generate");
|
| 183 |
-
const [imageSize, setImageSize] = useState("
|
| 184 |
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
|
| 185 |
const [referenceImageFiles, setReferenceImageFiles] = useState<File[]>([]);
|
| 186 |
const [referenceImages, setReferenceImages] = useState<StoredReferenceImage[]>([]);
|
|
@@ -216,9 +216,7 @@ export default function ImagePage() {
|
|
| 216 |
const loadHistory = async () => {
|
| 217 |
try {
|
| 218 |
const storedSize = typeof window !== "undefined" ? window.localStorage.getItem(IMAGE_SIZE_STORAGE_KEY) : null;
|
| 219 |
-
|
| 220 |
-
setImageSize(storedSize);
|
| 221 |
-
}
|
| 222 |
|
| 223 |
const items = await listImageConversations();
|
| 224 |
const normalizedItems = await recoverConversationHistory(items);
|
|
@@ -307,7 +305,9 @@ export default function ImagePage() {
|
|
| 307 |
|
| 308 |
if (imageSize) {
|
| 309 |
window.localStorage.setItem(IMAGE_SIZE_STORAGE_KEY, imageSize);
|
|
|
|
| 310 |
}
|
|
|
|
| 311 |
}, [imageSize]);
|
| 312 |
|
| 313 |
useEffect(() => {
|
|
@@ -819,6 +819,14 @@ export default function ImagePage() {
|
|
| 819 |
<Plus className="size-4" />
|
| 820 |
新建
|
| 821 |
</Button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 822 |
</div>
|
| 823 |
|
| 824 |
<div
|
|
|
|
| 1 |
"use client";
|
| 2 |
|
| 3 |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 4 |
+
import { History, Plus, Trash2 } from "lucide-react";
|
| 5 |
import { toast } from "sonner";
|
| 6 |
|
| 7 |
import { ImageComposer } from "@/app/image/components/image-composer";
|
|
|
|
| 180 |
const [imagePrompt, setImagePrompt] = useState("");
|
| 181 |
const [imageCount, setImageCount] = useState("1");
|
| 182 |
const [imageMode, setImageMode] = useState<ImageConversationMode>("generate");
|
| 183 |
+
const [imageSize, setImageSize] = useState("");
|
| 184 |
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
|
| 185 |
const [referenceImageFiles, setReferenceImageFiles] = useState<File[]>([]);
|
| 186 |
const [referenceImages, setReferenceImages] = useState<StoredReferenceImage[]>([]);
|
|
|
|
| 216 |
const loadHistory = async () => {
|
| 217 |
try {
|
| 218 |
const storedSize = typeof window !== "undefined" ? window.localStorage.getItem(IMAGE_SIZE_STORAGE_KEY) : null;
|
| 219 |
+
setImageSize(storedSize || "");
|
|
|
|
|
|
|
| 220 |
|
| 221 |
const items = await listImageConversations();
|
| 222 |
const normalizedItems = await recoverConversationHistory(items);
|
|
|
|
| 305 |
|
| 306 |
if (imageSize) {
|
| 307 |
window.localStorage.setItem(IMAGE_SIZE_STORAGE_KEY, imageSize);
|
| 308 |
+
return;
|
| 309 |
}
|
| 310 |
+
window.localStorage.removeItem(IMAGE_SIZE_STORAGE_KEY);
|
| 311 |
}, [imageSize]);
|
| 312 |
|
| 313 |
useEffect(() => {
|
|
|
|
| 819 |
<Plus className="size-4" />
|
| 820 |
新建
|
| 821 |
</Button>
|
| 822 |
+
<Button
|
| 823 |
+
variant="outline"
|
| 824 |
+
className="h-10 rounded-2xl border-stone-200 bg-white/85 px-3 text-stone-600 shadow-sm"
|
| 825 |
+
onClick={() => void handleClearHistory()}
|
| 826 |
+
disabled={conversations.length === 0}
|
| 827 |
+
>
|
| 828 |
+
<Trash2 className="size-4" />
|
| 829 |
+
</Button>
|
| 830 |
</div>
|
| 831 |
|
| 832 |
<div
|
web/src/components/top-nav.tsx
CHANGED
|
@@ -28,7 +28,7 @@ export function TopNav() {
|
|
| 28 |
}
|
| 29 |
|
| 30 |
return (
|
| 31 |
-
<header className="border-b border-stone-100/50
|
| 32 |
<div className="flex h-12 items-center justify-between px-3 sm:px-6">
|
| 33 |
<div className="flex items-center gap-2 sm:gap-3">
|
| 34 |
<Link
|
|
|
|
| 28 |
}
|
| 29 |
|
| 30 |
return (
|
| 31 |
+
<header className="border-b border-stone-100/50">
|
| 32 |
<div className="flex h-12 items-center justify-between px-3 sm:px-6">
|
| 33 |
<div className="flex items-center gap-2 sm:gap-3">
|
| 34 |
<Link
|
web/src/lib/api.ts
CHANGED
|
@@ -111,7 +111,7 @@ export async function updateAccount(
|
|
| 111 |
});
|
| 112 |
}
|
| 113 |
|
| 114 |
-
export async function generateImage(prompt: string, model?: ImageModel, size: string
|
| 115 |
return httpRequest<{ created: number; data: Array<{ b64_json: string; revised_prompt?: string }> }>(
|
| 116 |
"/v1/images/generations",
|
| 117 |
{
|
|
@@ -119,7 +119,7 @@ export async function generateImage(prompt: string, model?: ImageModel, size: st
|
|
| 119 |
body: {
|
| 120 |
prompt,
|
| 121 |
...(model ? { model } : {}),
|
| 122 |
-
size,
|
| 123 |
n: 1,
|
| 124 |
response_format: "b64_json",
|
| 125 |
},
|
|
@@ -127,7 +127,7 @@ export async function generateImage(prompt: string, model?: ImageModel, size: st
|
|
| 127 |
);
|
| 128 |
}
|
| 129 |
|
| 130 |
-
export async function editImage(files: File | File[], prompt: string, model?: ImageModel, size: string
|
| 131 |
const formData = new FormData();
|
| 132 |
const uploadFiles = Array.isArray(files) ? files : [files];
|
| 133 |
|
|
@@ -138,7 +138,9 @@ export async function editImage(files: File | File[], prompt: string, model?: Im
|
|
| 138 |
if (model) {
|
| 139 |
formData.append("model", model);
|
| 140 |
}
|
| 141 |
-
|
|
|
|
|
|
|
| 142 |
formData.append("n", "1");
|
| 143 |
|
| 144 |
return httpRequest<{ created: number; data: Array<{ b64_json: string; revised_prompt?: string }> }>(
|
|
|
|
| 111 |
});
|
| 112 |
}
|
| 113 |
|
| 114 |
+
export async function generateImage(prompt: string, model?: ImageModel, size?: string) {
|
| 115 |
return httpRequest<{ created: number; data: Array<{ b64_json: string; revised_prompt?: string }> }>(
|
| 116 |
"/v1/images/generations",
|
| 117 |
{
|
|
|
|
| 119 |
body: {
|
| 120 |
prompt,
|
| 121 |
...(model ? { model } : {}),
|
| 122 |
+
...(size ? { size } : {}),
|
| 123 |
n: 1,
|
| 124 |
response_format: "b64_json",
|
| 125 |
},
|
|
|
|
| 127 |
);
|
| 128 |
}
|
| 129 |
|
| 130 |
+
export async function editImage(files: File | File[], prompt: string, model?: ImageModel, size?: string) {
|
| 131 |
const formData = new FormData();
|
| 132 |
const uploadFiles = Array.isArray(files) ? files : [files];
|
| 133 |
|
|
|
|
| 138 |
if (model) {
|
| 139 |
formData.append("model", model);
|
| 140 |
}
|
| 141 |
+
if (size) {
|
| 142 |
+
formData.append("size", size);
|
| 143 |
+
}
|
| 144 |
formData.append("n", "1");
|
| 145 |
|
| 146 |
return httpRequest<{ created: number; data: Array<{ b64_json: string; revised_prompt?: string }> }>(
|
web/src/store/image-conversations.ts
CHANGED
|
@@ -124,7 +124,7 @@ function normalizeTurn(turn: ImageTurn & Record<string, unknown>): ImageTurn {
|
|
| 124 |
mode: turn.mode === "edit" ? "edit" : "generate",
|
| 125 |
referenceImages: getLegacyReferenceImages(turn),
|
| 126 |
count: Math.max(1, Number(turn.count || normalizedImages.length || 1)),
|
| 127 |
-
size:
|
| 128 |
images: normalizedImages,
|
| 129 |
createdAt: String(turn.createdAt || new Date().toISOString()),
|
| 130 |
status:
|
|
@@ -149,7 +149,7 @@ function normalizeConversation(conversation: ImageConversation & Record<string,
|
|
| 149 |
mode: conversation.mode === "edit" ? "edit" : "generate",
|
| 150 |
referenceImages: getLegacyReferenceImages(conversation),
|
| 151 |
count: Number(conversation.count || 1),
|
| 152 |
-
size:
|
| 153 |
images: Array.isArray(conversation.images) ? (conversation.images as StoredImage[]) : [],
|
| 154 |
createdAt: String(conversation.createdAt || new Date().toISOString()),
|
| 155 |
status:
|
|
|
|
| 124 |
mode: turn.mode === "edit" ? "edit" : "generate",
|
| 125 |
referenceImages: getLegacyReferenceImages(turn),
|
| 126 |
count: Math.max(1, Number(turn.count || normalizedImages.length || 1)),
|
| 127 |
+
size: typeof turn.size === "string" ? turn.size : "",
|
| 128 |
images: normalizedImages,
|
| 129 |
createdAt: String(turn.createdAt || new Date().toISOString()),
|
| 130 |
status:
|
|
|
|
| 149 |
mode: conversation.mode === "edit" ? "edit" : "generate",
|
| 150 |
referenceImages: getLegacyReferenceImages(conversation),
|
| 151 |
count: Number(conversation.count || 1),
|
| 152 |
+
size: typeof conversation.size === "string" ? conversation.size : "",
|
| 153 |
images: Array.isArray(conversation.images) ? (conversation.images as StoredImage[]) : [],
|
| 154 |
createdAt: String(conversation.createdAt || new Date().toISOString()),
|
| 155 |
status:
|