Merge branch 'fork/CEastWind/feat/image-edit-url'
Browse files- README.md +18 -1
- api/image_inputs.py +269 -0
- api/image_tasks.py +10 -17
- test/test_image_tasks_api.py +22 -0
- test/test_v1_images_edits_api.py +72 -0
README.md
CHANGED
|
@@ -204,7 +204,7 @@ curl http://localhost:8000/v1/images/generations \
|
|
| 204 |
<summary><code>POST /v1/images/edits</code></summary>
|
| 205 |
<br>
|
| 206 |
|
| 207 |
-
OpenAI 兼容图片编辑接口,
|
| 208 |
|
| 209 |
```bash
|
| 210 |
curl http://localhost:8000/v1/images/edits \
|
|
@@ -215,6 +215,21 @@ curl http://localhost:8000/v1/images/edits \
|
|
| 215 |
-F "image=@./input.png"
|
| 216 |
```
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
<details>
|
| 219 |
<summary>字段说明</summary>
|
| 220 |
<br>
|
|
@@ -225,6 +240,8 @@ curl http://localhost:8000/v1/images/edits \
|
|
| 225 |
| `prompt` | 图片编辑提示词 |
|
| 226 |
| `n` | 生成数量,当前后端限制为 `1-4` |
|
| 227 |
| `image` | 需要编辑的图片文件,使用 multipart/form-data 上传 |
|
|
|
|
|
|
|
| 228 |
|
| 229 |
<br>
|
| 230 |
</details>
|
|
|
|
| 204 |
<summary><code>POST /v1/images/edits</code></summary>
|
| 205 |
<br>
|
| 206 |
|
| 207 |
+
OpenAI 兼容图片编辑接口,可上传图片文件,也可按官方 JSON 格式传入图片链接并生成编辑结果。
|
| 208 |
|
| 209 |
```bash
|
| 210 |
curl http://localhost:8000/v1/images/edits \
|
|
|
|
| 215 |
-F "image=@./input.png"
|
| 216 |
```
|
| 217 |
|
| 218 |
+
也可以直接传图片 URL:
|
| 219 |
+
|
| 220 |
+
```bash
|
| 221 |
+
curl http://localhost:8000/v1/images/edits \
|
| 222 |
+
-H "Authorization: Bearer <auth-key>" \
|
| 223 |
+
-H "Content-Type: application/json" \
|
| 224 |
+
-d '{
|
| 225 |
+
"model": "gpt-image-2",
|
| 226 |
+
"prompt": "把这张图改成赛博朋克夜景风格",
|
| 227 |
+
"images": [
|
| 228 |
+
{"image_url": "https://example.com/input.png"}
|
| 229 |
+
]
|
| 230 |
+
}'
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
<details>
|
| 234 |
<summary>字段说明</summary>
|
| 235 |
<br>
|
|
|
|
| 240 |
| `prompt` | 图片编辑提示词 |
|
| 241 |
| `n` | 生成数量,当前后端限制为 `1-4` |
|
| 242 |
| `image` | 需要编辑的图片文件,使用 multipart/form-data 上传 |
|
| 243 |
+
| `images` | JSON 图片引用数组,支持 `{"image_url": "https://..."}` |
|
| 244 |
+
| `image_url` | 表单模式下也可直接传图片链接,支持重复字段传多张图 |
|
| 245 |
|
| 246 |
<br>
|
| 247 |
</details>
|
api/image_inputs.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import binascii
|
| 5 |
+
import json
|
| 6 |
+
import mimetypes
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import PurePosixPath
|
| 9 |
+
from typing import Any, TypeGuard
|
| 10 |
+
from urllib.parse import unquote, unquote_to_bytes, urlparse
|
| 11 |
+
|
| 12 |
+
from curl_cffi import requests
|
| 13 |
+
from fastapi import HTTPException, Request
|
| 14 |
+
from fastapi.concurrency import run_in_threadpool
|
| 15 |
+
from starlette.datastructures import UploadFile
|
| 16 |
+
|
| 17 |
+
from services.proxy_service import proxy_settings
|
| 18 |
+
|
| 19 |
+
ImageInput = tuple[bytes, str, str]
|
| 20 |
+
ImageSource = str | UploadFile
|
| 21 |
+
|
| 22 |
+
MAX_IMAGE_REFERENCE_BYTES = 50 * 1024 * 1024
|
| 23 |
+
IMAGE_REFERENCE_FIELDS = {"image", "image[]", "images", "images[]", "image_url", "image_url[]"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _clean(value: object, default: str = "") -> str:
|
| 27 |
+
"""清理字符串:转换为字符串并去掉首尾空白。"""
|
| 28 |
+
text = str(value if value is not None else default).strip()
|
| 29 |
+
return text or default
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _is_upload(value: object) -> TypeGuard[UploadFile]:
|
| 33 |
+
"""识别上传文件:兼容 Starlette 表单返回的 UploadFile。"""
|
| 34 |
+
return isinstance(value, UploadFile)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _parse_bool(value: object) -> bool | None:
|
| 38 |
+
"""解析布尔字段:兼容 JSON 布尔值和表单字符串。"""
|
| 39 |
+
if value is None or value == "":
|
| 40 |
+
return None
|
| 41 |
+
if isinstance(value, bool):
|
| 42 |
+
return value
|
| 43 |
+
text = _clean(value).lower()
|
| 44 |
+
if text in {"true", "1", "yes", "y", "on"}:
|
| 45 |
+
return True
|
| 46 |
+
if text in {"false", "0", "no", "n", "off"}:
|
| 47 |
+
return False
|
| 48 |
+
raise HTTPException(status_code=400, detail={"error": "stream must be a boolean"})
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _parse_count(value: object) -> int:
|
| 52 |
+
"""解析生成数量:保持图片接口的 1 到 4 限制。"""
|
| 53 |
+
try:
|
| 54 |
+
count = int(value or 1)
|
| 55 |
+
except (TypeError, ValueError) as exc:
|
| 56 |
+
raise HTTPException(status_code=400, detail={"error": "n must be an integer"}) from exc
|
| 57 |
+
if count < 1 or count > 4:
|
| 58 |
+
raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
|
| 59 |
+
return count
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _payload_from_fields(fields: dict[str, Any]) -> dict[str, Any]:
|
| 63 |
+
"""构造图片编辑载荷:从表单或 JSON 字段提取通用参数。"""
|
| 64 |
+
prompt = _clean(fields.get("prompt"))
|
| 65 |
+
if not prompt:
|
| 66 |
+
raise HTTPException(status_code=400, detail={"error": "prompt is required"})
|
| 67 |
+
payload = {
|
| 68 |
+
"prompt": prompt,
|
| 69 |
+
"model": _clean(fields.get("model"), "gpt-image-2"),
|
| 70 |
+
"n": _parse_count(fields.get("n")),
|
| 71 |
+
"size": _clean(fields.get("size")) or None,
|
| 72 |
+
"response_format": _clean(fields.get("response_format"), "b64_json"),
|
| 73 |
+
"stream": _parse_bool(fields.get("stream")),
|
| 74 |
+
}
|
| 75 |
+
if "client_task_id" in fields:
|
| 76 |
+
payload["client_task_id"] = _clean(fields.get("client_task_id"))
|
| 77 |
+
return payload
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _json_reference_value(value: object) -> object:
|
| 81 |
+
"""解析表单图片引用:支持把 images 字段写成 JSON 字符串。"""
|
| 82 |
+
if not isinstance(value, str):
|
| 83 |
+
return value
|
| 84 |
+
text = value.strip()
|
| 85 |
+
if not text or text[0] not in "[{":
|
| 86 |
+
return value
|
| 87 |
+
try:
|
| 88 |
+
return json.loads(text)
|
| 89 |
+
except json.JSONDecodeError:
|
| 90 |
+
return value
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _source_from_object(value: dict[str, Any]) -> list[ImageSource]:
|
| 94 |
+
"""提取图片引用对象:支持 image_url 或 url,明确拒绝 file_id。"""
|
| 95 |
+
has_url = "image_url" in value or "url" in value
|
| 96 |
+
if value.get("file_id"):
|
| 97 |
+
raise HTTPException(
|
| 98 |
+
status_code=400,
|
| 99 |
+
detail={"error": "file_id image references are not supported; use image_url instead"},
|
| 100 |
+
)
|
| 101 |
+
if not has_url:
|
| 102 |
+
raise HTTPException(status_code=400, detail={"error": "image reference must include image_url"})
|
| 103 |
+
image_url = value.get("image_url", value.get("url"))
|
| 104 |
+
if isinstance(image_url, dict):
|
| 105 |
+
image_url = image_url.get("url")
|
| 106 |
+
return _sources_from_value(image_url)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _sources_from_value(value: object) -> list[ImageSource]:
|
| 110 |
+
"""展开图片引用:把字符串、数组和对象统一成图片来源列表。"""
|
| 111 |
+
value = _json_reference_value(value)
|
| 112 |
+
if _is_upload(value):
|
| 113 |
+
return [value]
|
| 114 |
+
if isinstance(value, str):
|
| 115 |
+
text = value.strip()
|
| 116 |
+
return [text] if text else []
|
| 117 |
+
if isinstance(value, list):
|
| 118 |
+
sources: list[ImageSource] = []
|
| 119 |
+
for item in value:
|
| 120 |
+
sources.extend(_sources_from_value(item))
|
| 121 |
+
return sources
|
| 122 |
+
if isinstance(value, dict):
|
| 123 |
+
return _source_from_object(value)
|
| 124 |
+
if value is None:
|
| 125 |
+
return []
|
| 126 |
+
raise HTTPException(status_code=400, detail={"error": "invalid image reference"})
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _json_image_sources(body: dict[str, Any]) -> list[ImageSource]:
|
| 130 |
+
"""读取 JSON 图片引用:优先支持官方 images 数组字段。"""
|
| 131 |
+
sources: list[ImageSource] = []
|
| 132 |
+
for key in ("images", "image", "image_url"):
|
| 133 |
+
if key in body:
|
| 134 |
+
sources.extend(_sources_from_value(body.get(key)))
|
| 135 |
+
return sources
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
async def parse_image_edit_request(request: Request) -> tuple[dict[str, Any], list[ImageSource]]:
|
| 139 |
+
"""解析图片编辑请求:同时支持 multipart 上传和官方 JSON 图片 URL。"""
|
| 140 |
+
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
| 141 |
+
if content_type == "application/json":
|
| 142 |
+
try:
|
| 143 |
+
body = await request.json()
|
| 144 |
+
except json.JSONDecodeError as exc:
|
| 145 |
+
raise HTTPException(status_code=400, detail={"error": "invalid JSON body"}) from exc
|
| 146 |
+
if not isinstance(body, dict):
|
| 147 |
+
raise HTTPException(status_code=400, detail={"error": "JSON body must be an object"})
|
| 148 |
+
return _payload_from_fields(body), _json_image_sources(body)
|
| 149 |
+
|
| 150 |
+
form = await request.form()
|
| 151 |
+
fields: dict[str, Any] = {}
|
| 152 |
+
for key in ("client_task_id", "prompt", "model", "n", "size", "response_format", "stream"):
|
| 153 |
+
value = form.get(key)
|
| 154 |
+
if isinstance(value, str):
|
| 155 |
+
fields[key] = value
|
| 156 |
+
sources: list[ImageSource] = []
|
| 157 |
+
for key, value in form.multi_items():
|
| 158 |
+
if key in IMAGE_REFERENCE_FIELDS:
|
| 159 |
+
sources.extend(_sources_from_value(value))
|
| 160 |
+
return _payload_from_fields(fields), sources
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _extension_from_mime(mime_type: str) -> str:
|
| 164 |
+
"""推导图片扩展名:把 MIME 类型转换为常见文件后缀。"""
|
| 165 |
+
subtype = mime_type.split("/", 1)[1].split("+", 1)[0] if "/" in mime_type else "png"
|
| 166 |
+
if subtype == "jpeg":
|
| 167 |
+
return "jpg"
|
| 168 |
+
return re.sub(r"[^a-z0-9]+", "", subtype.lower()) or "png"
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _safe_filename(name: str, mime_type: str, fallback: str) -> str:
|
| 172 |
+
"""生成安全文件名:清理 URL 文件名并补齐扩展名。"""
|
| 173 |
+
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("._")
|
| 174 |
+
if not cleaned:
|
| 175 |
+
cleaned = fallback
|
| 176 |
+
if "." not in cleaned:
|
| 177 |
+
cleaned = f"{cleaned}.{_extension_from_mime(mime_type)}"
|
| 178 |
+
return cleaned
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _decode_data_url(url: str) -> ImageInput:
|
| 182 |
+
"""解码 data URL:把内联图片转成标准图片输入元组。"""
|
| 183 |
+
header, separator, payload = url.partition(",")
|
| 184 |
+
if not separator:
|
| 185 |
+
raise HTTPException(status_code=400, detail={"error": "invalid data image URL"})
|
| 186 |
+
mime_type = header.split(";", 1)[0].removeprefix("data:") or "image/png"
|
| 187 |
+
if not mime_type.startswith("image/"):
|
| 188 |
+
raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
|
| 189 |
+
try:
|
| 190 |
+
data = base64.b64decode(payload, validate=True) if ";base64" in header else unquote_to_bytes(payload)
|
| 191 |
+
except (binascii.Error, ValueError) as exc:
|
| 192 |
+
raise HTTPException(status_code=400, detail={"error": "invalid data image URL"}) from exc
|
| 193 |
+
if not data:
|
| 194 |
+
raise HTTPException(status_code=400, detail={"error": "image URL is empty"})
|
| 195 |
+
if len(data) > MAX_IMAGE_REFERENCE_BYTES:
|
| 196 |
+
raise HTTPException(status_code=400, detail={"error": "image URL exceeds 50MB limit"})
|
| 197 |
+
return data, f"image_url.{_extension_from_mime(mime_type)}", mime_type
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _response_mime_type(response: requests.Response, parsed_path: str) -> str:
|
| 201 |
+
"""识别下载图片类型:优先响应头,必要时按 URL 后缀推断。"""
|
| 202 |
+
header_type = str(response.headers.get("content-type") or "").split(";", 1)[0].strip().lower()
|
| 203 |
+
guessed_type = mimetypes.guess_type(parsed_path)[0] or ""
|
| 204 |
+
if header_type.startswith("image/"):
|
| 205 |
+
return header_type
|
| 206 |
+
if header_type and header_type not in {"application/octet-stream", "binary/octet-stream"}:
|
| 207 |
+
raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
|
| 208 |
+
if guessed_type.startswith("image/"):
|
| 209 |
+
return guessed_type
|
| 210 |
+
if not header_type or header_type in {"application/octet-stream", "binary/octet-stream"}:
|
| 211 |
+
return "image/png"
|
| 212 |
+
raise HTTPException(status_code=400, detail={"error": "image_url must point to an image"})
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _filename_from_url(parsed_path: str, mime_type: str) -> str:
|
| 216 |
+
"""生成 URL 图片文件名:从链接路径提取名称并做安全化。"""
|
| 217 |
+
raw_name = PurePosixPath(unquote(parsed_path)).name
|
| 218 |
+
return _safe_filename(raw_name, mime_type, "image_url")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _download_image_url(url: str) -> ImageInput:
|
| 222 |
+
"""下载远程图片:把 http/https 图片链接转成标准图片输入元组。"""
|
| 223 |
+
source = _clean(url)
|
| 224 |
+
if source.startswith("data:"):
|
| 225 |
+
return _decode_data_url(source)
|
| 226 |
+
parsed = urlparse(source)
|
| 227 |
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
| 228 |
+
raise HTTPException(status_code=400, detail={"error": "image_url must be an http or https URL"})
|
| 229 |
+
try:
|
| 230 |
+
response = requests.get(
|
| 231 |
+
source,
|
| 232 |
+
headers={"Accept": "image/*,*/*;q=0.8", "User-Agent": "chatgpt2api image fetcher"},
|
| 233 |
+
timeout=60,
|
| 234 |
+
allow_redirects=True,
|
| 235 |
+
**proxy_settings.build_session_kwargs(),
|
| 236 |
+
)
|
| 237 |
+
except Exception as exc:
|
| 238 |
+
raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: {exc}"}) from exc
|
| 239 |
+
if not 200 <= response.status_code < 300:
|
| 240 |
+
raise HTTPException(status_code=400, detail={"error": f"image_url fetch failed: HTTP {response.status_code}"})
|
| 241 |
+
content_length = _clean(response.headers.get("content-length"))
|
| 242 |
+
if content_length and content_length.isdigit() and int(content_length) > MAX_IMAGE_REFERENCE_BYTES:
|
| 243 |
+
raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
|
| 244 |
+
data = response.content
|
| 245 |
+
if not data:
|
| 246 |
+
raise HTTPException(status_code=400, detail={"error": "image_url returned empty content"})
|
| 247 |
+
if len(data) > MAX_IMAGE_REFERENCE_BYTES:
|
| 248 |
+
raise HTTPException(status_code=400, detail={"error": "image_url exceeds 50MB limit"})
|
| 249 |
+
mime_type = _response_mime_type(response, parsed.path)
|
| 250 |
+
return data, _filename_from_url(parsed.path, mime_type), mime_type
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
async def read_image_sources(sources: list[ImageSource]) -> list[ImageInput]:
|
| 254 |
+
"""读取图片来源:上传文件直接读取,URL 下载后统一返回图片元组。"""
|
| 255 |
+
images: list[ImageInput] = []
|
| 256 |
+
for source in sources:
|
| 257 |
+
if _is_upload(source):
|
| 258 |
+
try:
|
| 259 |
+
image_data = await source.read()
|
| 260 |
+
finally:
|
| 261 |
+
await source.close()
|
| 262 |
+
if not image_data:
|
| 263 |
+
raise HTTPException(status_code=400, detail={"error": "image file is empty"})
|
| 264 |
+
images.append((image_data, source.filename or "image.png", source.content_type or "image/png"))
|
| 265 |
+
continue
|
| 266 |
+
images.append(await run_in_threadpool(_download_image_url, source))
|
| 267 |
+
if not images:
|
| 268 |
+
raise HTTPException(status_code=400, detail={"error": "image file or image_url is required"})
|
| 269 |
+
return images
|
api/image_tasks.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
-
from fastapi import APIRouter,
|
| 4 |
from fastapi.concurrency import run_in_threadpool
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
|
|
|
|
| 7 |
from api.support import require_identity, resolve_image_base_url
|
| 8 |
from services.content_filter import check_request
|
| 9 |
from services.image_task_service import image_task_service
|
|
@@ -65,24 +66,16 @@ def create_router() -> APIRouter:
|
|
| 65 |
async def create_edit_task(
|
| 66 |
request: Request,
|
| 67 |
authorization: str | None = Header(default=None),
|
| 68 |
-
image: list[UploadFile] | None = File(default=None),
|
| 69 |
-
image_list: list[UploadFile] | None = File(default=None, alias="image[]"),
|
| 70 |
-
client_task_id: str = Form(...),
|
| 71 |
-
prompt: str = Form(...),
|
| 72 |
-
model: str = Form(default="gpt-image-2"),
|
| 73 |
-
size: str | None = Form(default=None),
|
| 74 |
):
|
| 75 |
identity = require_identity(authorization)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
await filter_or_log(LoggedCall(identity, "/api/image-tasks/edits", model, "图生图任务", request_text=prompt), prompt)
|
| 77 |
-
|
| 78 |
-
if not uploads:
|
| 79 |
-
raise HTTPException(status_code=400, detail={"error": "image file is required"})
|
| 80 |
-
images: list[tuple[bytes, str, str]] = []
|
| 81 |
-
for upload in uploads:
|
| 82 |
-
image_data = await upload.read()
|
| 83 |
-
if not image_data:
|
| 84 |
-
raise HTTPException(status_code=400, detail={"error": "image file is empty"})
|
| 85 |
-
images.append((image_data, upload.filename or "image.png", upload.content_type or "image/png"))
|
| 86 |
try:
|
| 87 |
return await run_in_threadpool(
|
| 88 |
image_task_service.submit_edit,
|
|
@@ -90,7 +83,7 @@ def create_router() -> APIRouter:
|
|
| 90 |
client_task_id=client_task_id,
|
| 91 |
prompt=prompt,
|
| 92 |
model=model,
|
| 93 |
-
size=size,
|
| 94 |
base_url=resolve_image_base_url(request),
|
| 95 |
images=images,
|
| 96 |
)
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
from fastapi import APIRouter, Header, HTTPException, Query, Request
|
| 4 |
from fastapi.concurrency import run_in_threadpool
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
|
| 7 |
+
from api.image_inputs import parse_image_edit_request, read_image_sources
|
| 8 |
from api.support import require_identity, resolve_image_base_url
|
| 9 |
from services.content_filter import check_request
|
| 10 |
from services.image_task_service import image_task_service
|
|
|
|
| 66 |
async def create_edit_task(
|
| 67 |
request: Request,
|
| 68 |
authorization: str | None = Header(default=None),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
):
|
| 70 |
identity = require_identity(authorization)
|
| 71 |
+
payload, image_sources = await parse_image_edit_request(request)
|
| 72 |
+
client_task_id = str(payload.get("client_task_id") or "").strip()
|
| 73 |
+
if not client_task_id:
|
| 74 |
+
raise HTTPException(status_code=400, detail={"error": "client_task_id is required"})
|
| 75 |
+
prompt = str(payload["prompt"])
|
| 76 |
+
model = str(payload["model"])
|
| 77 |
await filter_or_log(LoggedCall(identity, "/api/image-tasks/edits", model, "图生图任务", request_text=prompt), prompt)
|
| 78 |
+
images = await read_image_sources(image_sources)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
try:
|
| 80 |
return await run_in_threadpool(
|
| 81 |
image_task_service.submit_edit,
|
|
|
|
| 83 |
client_task_id=client_task_id,
|
| 84 |
prompt=prompt,
|
| 85 |
model=model,
|
| 86 |
+
size=payload["size"],
|
| 87 |
base_url=resolve_image_base_url(request),
|
| 88 |
images=images,
|
| 89 |
)
|
test/test_image_tasks_api.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import unittest
|
| 4 |
from unittest import mock
|
| 5 |
|
|
@@ -10,6 +11,8 @@ import api.image_tasks as image_tasks_module
|
|
| 10 |
|
| 11 |
|
| 12 |
AUTH_HEADERS = {"Authorization": "Bearer chatgpt2api"}
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
class FakeImageTaskService:
|
|
@@ -80,6 +83,7 @@ class ImageTasksApiTests(unittest.TestCase):
|
|
| 80 |
self.assertEqual(len(self.fake_service.generation_calls), 1)
|
| 81 |
|
| 82 |
def test_create_edit_task_accepts_multiple_images(self):
|
|
|
|
| 83 |
response = self.client.post(
|
| 84 |
"/api/image-tasks/edits",
|
| 85 |
headers=AUTH_HEADERS,
|
|
@@ -96,6 +100,24 @@ class ImageTasksApiTests(unittest.TestCase):
|
|
| 96 |
images = self.fake_service.edit_calls[0][1]["images"]
|
| 97 |
self.assertEqual(len(images), 2)
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
def test_list_tasks_reports_missing_ids(self):
|
| 100 |
response = self.client.get("/api/image-tasks?ids=task-1,missing", headers=AUTH_HEADERS)
|
| 101 |
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import base64
|
| 4 |
import unittest
|
| 5 |
from unittest import mock
|
| 6 |
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
AUTH_HEADERS = {"Authorization": "Bearer chatgpt2api"}
|
| 14 |
+
PNG_BYTES = b"\x89PNG\r\n\x1a\n"
|
| 15 |
+
DATA_IMAGE_URL = f"data:image/png;base64,{base64.b64encode(PNG_BYTES).decode('ascii')}"
|
| 16 |
|
| 17 |
|
| 18 |
class FakeImageTaskService:
|
|
|
|
| 83 |
self.assertEqual(len(self.fake_service.generation_calls), 1)
|
| 84 |
|
| 85 |
def test_create_edit_task_accepts_multiple_images(self):
|
| 86 |
+
"""测试图片编辑任务接口支持多个上传图片。"""
|
| 87 |
response = self.client.post(
|
| 88 |
"/api/image-tasks/edits",
|
| 89 |
headers=AUTH_HEADERS,
|
|
|
|
| 100 |
images = self.fake_service.edit_calls[0][1]["images"]
|
| 101 |
self.assertEqual(len(images), 2)
|
| 102 |
|
| 103 |
+
def test_create_edit_task_accepts_image_url(self):
|
| 104 |
+
"""测试图片编辑任务接口支持表单 image_url 引用。"""
|
| 105 |
+
response = self.client.post(
|
| 106 |
+
"/api/image-tasks/edits",
|
| 107 |
+
headers=AUTH_HEADERS,
|
| 108 |
+
data={
|
| 109 |
+
"client_task_id": "edit-url-1",
|
| 110 |
+
"prompt": "edit",
|
| 111 |
+
"model": "gpt-image-2",
|
| 112 |
+
"image_url": DATA_IMAGE_URL,
|
| 113 |
+
},
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.assertEqual(response.status_code, 200, response.text)
|
| 117 |
+
self.assertEqual(len(self.fake_service.edit_calls), 1)
|
| 118 |
+
images = self.fake_service.edit_calls[0][1]["images"]
|
| 119 |
+
self.assertEqual(images, [(PNG_BYTES, "image_url.png", "image/png")])
|
| 120 |
+
|
| 121 |
def test_list_tasks_reports_missing_ids(self):
|
| 122 |
response = self.client.get("/api/image-tasks?ids=task-1,missing", headers=AUTH_HEADERS)
|
| 123 |
|
test/test_v1_images_edits_api.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import unittest
|
| 5 |
+
from unittest import mock
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI
|
| 8 |
+
from fastapi.testclient import TestClient
|
| 9 |
+
|
| 10 |
+
import api.ai as ai_module
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
AUTH_HEADERS = {"Authorization": "Bearer chatgpt2api"}
|
| 14 |
+
PNG_BYTES = b"\x89PNG\r\n\x1a\n"
|
| 15 |
+
DATA_IMAGE_URL = f"data:image/png;base64,{base64.b64encode(PNG_BYTES).decode('ascii')}"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ImagesEditsApiTests(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.handle_calls = []
|
| 21 |
+
|
| 22 |
+
def fake_handle(payload):
|
| 23 |
+
self.handle_calls.append(payload)
|
| 24 |
+
return {"created": 1, "data": [{"b64_json": base64.b64encode(b"out").decode("ascii")}]}
|
| 25 |
+
|
| 26 |
+
self.handler_patcher = mock.patch.object(ai_module.openai_v1_image_edit, "handle", fake_handle)
|
| 27 |
+
self.handler_patcher.start()
|
| 28 |
+
self.addCleanup(self.handler_patcher.stop)
|
| 29 |
+
app = FastAPI()
|
| 30 |
+
app.include_router(ai_module.create_router())
|
| 31 |
+
self.client = TestClient(app)
|
| 32 |
+
|
| 33 |
+
def test_edit_accepts_json_image_url(self):
|
| 34 |
+
"""测试图片编辑接口支持官方 JSON image_url 引用。"""
|
| 35 |
+
response = self.client.post(
|
| 36 |
+
"/v1/images/edits",
|
| 37 |
+
headers=AUTH_HEADERS,
|
| 38 |
+
json={
|
| 39 |
+
"model": "gpt-image-2",
|
| 40 |
+
"prompt": "edit",
|
| 41 |
+
"images": [{"image_url": DATA_IMAGE_URL}],
|
| 42 |
+
"n": 1,
|
| 43 |
+
"response_format": "b64_json",
|
| 44 |
+
},
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.assertEqual(response.status_code, 200, response.text)
|
| 48 |
+
self.assertEqual(len(self.handle_calls), 1)
|
| 49 |
+
payload = self.handle_calls[0]
|
| 50 |
+
self.assertEqual(payload["prompt"], "edit")
|
| 51 |
+
self.assertEqual(payload["n"], 1)
|
| 52 |
+
self.assertEqual(payload["images"], [(PNG_BYTES, "image_url.png", "image/png")])
|
| 53 |
+
|
| 54 |
+
def test_edit_rejects_file_id_reference(self):
|
| 55 |
+
"""测试图片编辑接口对暂不支持的 file_id 返回明确错误。"""
|
| 56 |
+
response = self.client.post(
|
| 57 |
+
"/v1/images/edits",
|
| 58 |
+
headers=AUTH_HEADERS,
|
| 59 |
+
json={
|
| 60 |
+
"model": "gpt-image-2",
|
| 61 |
+
"prompt": "edit",
|
| 62 |
+
"images": [{"file_id": "file-abc123"}],
|
| 63 |
+
},
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
self.assertEqual(response.status_code, 400, response.text)
|
| 67 |
+
self.assertIn("file_id image references are not supported", response.text)
|
| 68 |
+
self.assertEqual(self.handle_calls, [])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
unittest.main()
|