Compare commits
2 Commits
master
...
9426ac3a16
| Author | SHA1 | Date | |
|---|---|---|---|
| 9426ac3a16 | |||
| e999602f66 |
@@ -0,0 +1,75 @@
|
||||
# UI 编辑器自动分离工作流
|
||||
|
||||
更新时间:`2026-09-08`
|
||||
|
||||
## 目标
|
||||
|
||||
将 UI 编辑器现有“用户先提供独立图片/图标,再执行组件绑定”的入口替换为自动分离:结构识别阶段直接返回可渲染组件草稿,分离阶段按整页叶节点批次调用图片编辑模型,再由视觉模型确认处理图中的区域与目标节点。
|
||||
|
||||
## 识别结果
|
||||
|
||||
- `recognize` 返回完整 `Node.components` 草稿,不再要求用户先导入独立素材。
|
||||
- `components` 为空表示纯节点。
|
||||
- `ImageComponent.target_graphic = None` 表示图片组件等待分离结果回填;它不是“明确没有图片”。
|
||||
- 当前约束:需要分离的节点最多包含一个 `ImageComponent`,回填暂使用该节点的第一个图片组件。
|
||||
- 组件容器“一种组件类型最多一个”的正式重构列为 TODO;当前 `Vec<Component>` 仅按上述约束使用。
|
||||
- 组件草稿直接保存在正式 UI Node 中;临时 separation tree 不复制组件。
|
||||
|
||||
## Separation tree
|
||||
|
||||
- recognition 完成后由 UI tree 构造临时 separation tree。
|
||||
- 纯节点、纯 Text 节点和不需要切图的节点在构造时过滤;被过滤节点的可处理 children 向上透传。
|
||||
- separation tree 只保留真实待处理节点。
|
||||
- 一个 batch 是整页当前所有互不重叠叶节点。
|
||||
- 一个 batch 的最小处理单元是:一次 image-edit + 一次 visual binding。
|
||||
- batch 成功后从 pending tree 移除对应叶节点,并把结果放入 bound 容器;失败节点移入 problematic 容器,流程继续消费剩余树。
|
||||
- 不额外维护节点状态枚举;节点是否仍在 pending tree、`rework_count` 和 problematic 容器共同表达状态。
|
||||
|
||||
## 图片编辑与视觉绑定
|
||||
|
||||
- image-edit 使用源 UI design 图片及由 Rust 生成的绿色标记/紫色重建输入。
|
||||
- 请求尺寸始终使用源 UI design 尺寸;Raw GPT Image 2 API 保证返回相同尺寸,客户端不额外做尺寸拒绝检查。
|
||||
- 视觉 binding 输入源图与处理图,必须为当前 batch 每个节点恰好返回一次 `Ok` 或 `NeedRework`。
|
||||
- `Ok` 返回 `NodeId + BindingArea`;Rust 仅校验 NodeId、区域边界和非零尺寸,不检查与原节点框的偏差,也不要求区域不重叠。
|
||||
- `NeedRework` 携带短问题描述。结构化工具调用失败时使用可复用 repair harness,把错误反馈给模型并额外请求一次;image-edit 不使用该 harness。
|
||||
- 达到模块级重做常量后,节点移入 problematic;不中断整条工作流,最终统一通知用户。
|
||||
- 父节点背景重建由 image-edit 模型完成,不由 Rust 硬编码重建算法完成。
|
||||
|
||||
## 临时 sidecar
|
||||
|
||||
- separation 状态不写入 UI JSON,也不进入 manifest。
|
||||
- sidecar 目录按 UI manifest `asset_id` 生成,复用 `generated_file_stem(asset_id)` 的安全字符替换和 SHA-256 摘要规则,位于项目 `ui/` 下。
|
||||
- 目录只保存一份当前 separation state,而不是每 batch 一个状态文件。
|
||||
- state 文件只保留 `schema_version`、pending tree、bound 结果和 problematic 节点,不重复保存 `projectId / assetId / uiStateRevision`。
|
||||
- sidecar 只在 separation 未完成期间存在;完成后删除 state JSON。
|
||||
- 当前只持久化已经完成的 batch;正在执行 batch 的恢复语义列 TODO。
|
||||
- 临时图片可跨重启保留。raw image-edit 返回图、绿色/紫色标记图、处理图和 cut 图片当前都保留用于 debug;理论上只应在内存中,清理/归档策略列 TODO。
|
||||
|
||||
## bound 与 problematic
|
||||
|
||||
- bound 结果仅保存 `NodeId + cut_image_path`,不保存 `BindingArea` 或 component kind。
|
||||
- problematic 记录原始 NodeId、问题描述和 `rework_count`;原始 UI Node 保留不变。
|
||||
- `SeparationDTO` 不返回计数字段,只返回 `bound_nodes` 与 `problematic_nodes`。
|
||||
- separation Rust 流程不自动登记项目级 SpriteAsset。
|
||||
- 前端调用方消费 `SeparationDTO.bound_nodes`,复制/登记 cut 图片为项目级 SpriteAsset,再回填对应 Node 的第一个 Image component。
|
||||
- 每次重做产生新的 SpriteAssetId,不假设 NodeId 到 SpriteAssetId 的稳定映射。
|
||||
- sidecar 中的图片保留,正式 SpriteAsset 的最终清理策略列 TODO。
|
||||
|
||||
## 重启与 Raw GPT Image 2
|
||||
|
||||
- 已保存的 separation state 是跨重启继续工作的最小单位;重启后从上一个已保存 batch 的状态继续。
|
||||
- 当前执行中的 batch 是否持久化、以及如何避免 image-edit 成功后在 patch 前崩溃导致重复调用,列为 TODO。
|
||||
- Raw endpoint 每次 HTTP 调用都是一次新操作;客户端不保存或复用 raw operation ID,不实现第二套本地幂等账本。
|
||||
- 后端 raw operation 的持久状态与扣费后崩溃恢复窗口,遵循 Raw GPT Image 2 方案中的独立 TODO。
|
||||
|
||||
## TODO
|
||||
|
||||
- `Vec<Component>` 重构为一种组件类型最多一个的容器。
|
||||
- 当前第一个 Image component 回填规则的正式替代方案。
|
||||
- 正在执行 batch 的持久化和恢复。
|
||||
- 前端复制、登记 SpriteAsset、回填 State 的精确 IPC/提交合同。
|
||||
- 临时图片清理/归档策略。
|
||||
- 手动抠图能力。
|
||||
- problematic 对更高层 workflow 完成门禁的最终定义。
|
||||
- separation workflow 与 manifest/stage 的接入。
|
||||
- Raw GPT Image 2 后端 raw operation 持久状态及恢复 worker。
|
||||
@@ -50,6 +50,7 @@ pub fn build_router(state: AppState) -> Router {
|
||||
.merge(modules::platform::router(state.clone()))
|
||||
.merge(modules::external_generation::router(state.clone()))
|
||||
.merge(modules::platform_support::router(state.clone()))
|
||||
.merge(modules::raw::router(state.clone()))
|
||||
.merge(crate::error_reports::router(state.clone()))
|
||||
.route(
|
||||
"/api/profile/recharge/wechat/notify",
|
||||
|
||||
@@ -67,6 +67,7 @@ mod profile_identity;
|
||||
mod profile_recharge_expiration_listener;
|
||||
mod profile_recharge_refund_reconciliation;
|
||||
mod prompt;
|
||||
mod raw_image;
|
||||
mod refresh_session;
|
||||
mod registration_reward;
|
||||
mod request_context;
|
||||
|
||||
@@ -10,3 +10,4 @@ pub mod internal;
|
||||
pub mod platform;
|
||||
pub mod platform_support;
|
||||
pub mod profile;
|
||||
pub mod raw;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
use axum::{Router, middleware, routing::post};
|
||||
|
||||
use crate::{auth::require_bearer_auth, raw_image::edit_raw_image, state::AppState};
|
||||
|
||||
pub fn router(state: AppState) -> Router<AppState> {
|
||||
Router::new().route(
|
||||
"/api/raw/v1/images/edit",
|
||||
post(edit_raw_image)
|
||||
.route_layer(middleware::from_fn_with_state(state, require_bearer_auth)),
|
||||
)
|
||||
}
|
||||
@@ -414,7 +414,7 @@ impl OpenAiImageSettings {
|
||||
self
|
||||
}
|
||||
|
||||
fn provider_settings(&self) -> VectorEngineImageSettings {
|
||||
pub(crate) fn provider_settings(&self) -> VectorEngineImageSettings {
|
||||
VectorEngineImageSettings {
|
||||
base_url: self.base_url.clone(),
|
||||
api_key: self.api_key.clone(),
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Extension, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
|
||||
use platform_image::{RawImageEditOptions, ReferenceImage, create_vector_engine_raw_image_edit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
asset_billing::{
|
||||
execute_billable_asset_operation_with_cost, with_editor_generation_durable_billing_boundary,
|
||||
},
|
||||
auth::AuthenticatedAccessToken,
|
||||
http_error::AppError,
|
||||
openai_image_generation::{
|
||||
build_openai_image_http_client, map_platform_image_error, require_openai_image_settings,
|
||||
},
|
||||
request_context::RequestContext,
|
||||
state::AppState,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub(crate) struct RawImageData {
|
||||
pub(crate) data: String,
|
||||
pub(crate) mime_type: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub(crate) struct RawImageEditRequest {
|
||||
pub(crate) image: RawImageData,
|
||||
pub(crate) mask: Option<RawImageData>,
|
||||
pub(crate) prompt: String,
|
||||
pub(crate) quality: Option<String>,
|
||||
pub(crate) background: Option<String>,
|
||||
pub(crate) output_format: Option<String>,
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct RawImageEditItem {
|
||||
pub(crate) b64_json: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct RawImageEditResponse {
|
||||
pub(crate) data: Vec<RawImageEditItem>,
|
||||
}
|
||||
|
||||
pub(crate) async fn edit_raw_image(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_context): Extension<RequestContext>,
|
||||
Extension(authenticated): Extension<AuthenticatedAccessToken>,
|
||||
Json(payload): Json<RawImageEditRequest>,
|
||||
) -> Result<Json<Value>, AppError> {
|
||||
let prepared = prepare_request(payload)?;
|
||||
let settings = require_openai_image_settings(&state)?.with_external_api_audit_context(
|
||||
&request_context,
|
||||
Some(authenticated.claims().user_id().to_string()),
|
||||
None,
|
||||
);
|
||||
let http_client = build_openai_image_http_client(&settings)?;
|
||||
let provider_settings = settings.provider_settings();
|
||||
let user_id = authenticated.claims().user_id().to_string();
|
||||
let request_id = request_context.request_id().to_string();
|
||||
let points_cost = raw_image_edit_price(&state, prepared.width, prepared.height).await?;
|
||||
let operation = async move {
|
||||
let generated = create_vector_engine_raw_image_edit(
|
||||
&http_client,
|
||||
&provider_settings,
|
||||
prepared.prompt.as_str(),
|
||||
&prepared.image,
|
||||
prepared.options,
|
||||
"raw_image_edit",
|
||||
)
|
||||
.await
|
||||
.map_err(map_platform_image_error)?;
|
||||
let data = generated
|
||||
.images
|
||||
.into_iter()
|
||||
.map(|image| RawImageEditItem {
|
||||
b64_json: BASE64_STANDARD.encode(image.bytes),
|
||||
})
|
||||
.collect();
|
||||
Ok::<_, AppError>(RawImageEditResponse { data })
|
||||
};
|
||||
let result = with_editor_generation_durable_billing_boundary(
|
||||
execute_billable_asset_operation_with_cost(
|
||||
&state,
|
||||
user_id.as_str(),
|
||||
"raw-image-edit",
|
||||
request_id.as_str(),
|
||||
u64::from(points_cost),
|
||||
operation,
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(serde_json::to_value(result).map_err(|error| {
|
||||
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
|
||||
})?))
|
||||
}
|
||||
|
||||
struct PreparedRawImageEdit {
|
||||
image: ReferenceImage,
|
||||
prompt: String,
|
||||
options: RawImageEditOptions,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
fn prepare_request(payload: RawImageEditRequest) -> Result<PreparedRawImageEdit, AppError> {
|
||||
if payload.prompt.trim().is_empty() {
|
||||
return Err(bad_request("prompt 不能为空"));
|
||||
}
|
||||
if payload.width == 0 || payload.height == 0 {
|
||||
return Err(bad_request("width 和 height 必须为正整数"));
|
||||
}
|
||||
let image = decode_image(payload.image, "image")?;
|
||||
let mask = payload
|
||||
.mask
|
||||
.map(|value| decode_image(value, "mask"))
|
||||
.transpose()?;
|
||||
Ok(PreparedRawImageEdit {
|
||||
image,
|
||||
prompt: payload.prompt,
|
||||
options: RawImageEditOptions {
|
||||
quality: payload.quality,
|
||||
background: payload.background,
|
||||
output_format: payload.output_format,
|
||||
width: payload.width,
|
||||
height: payload.height,
|
||||
mask,
|
||||
},
|
||||
width: payload.width,
|
||||
height: payload.height,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_image(value: RawImageData, field: &str) -> Result<ReferenceImage, AppError> {
|
||||
let mime_type = value.mime_type.trim().to_string();
|
||||
if mime_type.is_empty() {
|
||||
return Err(bad_request(format!("{field}.mimeType 不能为空")));
|
||||
}
|
||||
let bytes = BASE64_STANDARD
|
||||
.decode(value.data.trim())
|
||||
.map_err(|error| bad_request(format!("{field}.data 必须是有效 base64:{error}")))?;
|
||||
Ok(ReferenceImage {
|
||||
bytes,
|
||||
file_name: format!("{field}.png"),
|
||||
mime_type,
|
||||
})
|
||||
}
|
||||
|
||||
async fn raw_image_edit_price(state: &AppState, width: u32, height: u32) -> Result<u32, AppError> {
|
||||
let tier = if width.max(height) > 1536 { "2K" } else { "1K" };
|
||||
state
|
||||
.editor_generation_pricing()
|
||||
.await
|
||||
.map(|pricing| {
|
||||
pricing.image_generation_mud_points(Some("quick-edit"), Some("gpt-image-2"), Some(tier))
|
||||
})
|
||||
.map_err(|error| {
|
||||
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_details(json!({
|
||||
"provider": "editor-generation-pricing",
|
||||
"message": error.to_string(),
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn bad_request(message: impl Into<String>) -> AppError {
|
||||
AppError::from_status(StatusCode::BAD_REQUEST).with_details(json!({
|
||||
"provider": "raw-image-edit",
|
||||
"message": message.into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_uses_one_image_object_and_rejects_images_array() {
|
||||
let payload = serde_json::json!({
|
||||
"image": {"data": "aGVsbG8=", "mimeType": "image/png"},
|
||||
"prompt": "edit",
|
||||
"width": 1024,
|
||||
"height": 1024
|
||||
});
|
||||
let parsed: RawImageEditRequest = serde_json::from_value(payload).expect("image object");
|
||||
let prepared = prepare_request(parsed).expect("request should prepare");
|
||||
assert_eq!(prepared.image.bytes, b"hello");
|
||||
|
||||
let array_payload = serde_json::json!({
|
||||
"images": [{"data": "aGVsbG8=", "mimeType": "image/png"}],
|
||||
"prompt": "edit",
|
||||
"width": 1024,
|
||||
"height": 1024
|
||||
});
|
||||
assert!(serde_json::from_value::<RawImageEditRequest>(array_payload).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_contains_only_data_b64_json() {
|
||||
let response = serde_json::to_value(RawImageEditResponse {
|
||||
data: vec![RawImageEditItem {
|
||||
b64_json: "aGVsbG8=".to_string(),
|
||||
}],
|
||||
})
|
||||
.expect("response should serialize");
|
||||
assert_eq!(
|
||||
response,
|
||||
serde_json::json!({"data": [{"b64_json": "aGVsbG8="}]})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,14 +10,15 @@ pub use pixel_art_snapper::{
|
||||
};
|
||||
pub use vector_engine::{
|
||||
DownloadedImage, GPT_IMAGE_2_C_MODEL, GPT_IMAGE_2_MODEL, GeneratedImages, NANOBANANA_2_MODEL,
|
||||
PlatformImageError, PlatformImageFailureAudit, PlatformImageStatusHint, ReferenceImage,
|
||||
VECTOR_ENGINE_GPT_IMAGE_2_MODEL, VECTOR_ENGINE_PROVIDER, VectorEngineImageSettings,
|
||||
build_vector_engine_image_http_client, build_vector_engine_image_request_body,
|
||||
PlatformImageError, PlatformImageFailureAudit, PlatformImageStatusHint, RawImageEditOptions,
|
||||
ReferenceImage, VECTOR_ENGINE_GPT_IMAGE_2_MODEL, VECTOR_ENGINE_PROVIDER,
|
||||
VectorEngineImageSettings, build_vector_engine_image_http_client,
|
||||
build_vector_engine_image_request_body,
|
||||
build_vector_engine_nanobanana_generate_content_request_body, create_vector_engine_image_edit,
|
||||
create_vector_engine_image_edit_with_references,
|
||||
create_vector_engine_image_edit_with_references_and_model,
|
||||
create_vector_engine_image_generation, create_vector_engine_image_generation_with_model,
|
||||
create_vector_engine_nanobanana_generate_content, download_remote_image,
|
||||
vector_engine_images_edit_url, vector_engine_images_generation_url,
|
||||
create_vector_engine_nanobanana_generate_content, create_vector_engine_raw_image_edit,
|
||||
download_remote_image, vector_engine_images_edit_url, vector_engine_images_generation_url,
|
||||
vector_engine_nanobanana_generate_content_url,
|
||||
};
|
||||
|
||||
@@ -16,6 +16,7 @@ use super::{
|
||||
curl_transport::{
|
||||
map_curl_error, send_vector_engine_json_request_with_curl,
|
||||
send_vector_engine_multipart_edit_request_with_curl,
|
||||
send_vector_engine_multipart_edit_request_with_curl_options,
|
||||
},
|
||||
error::PlatformImageError,
|
||||
image_source::resolve_reference_images,
|
||||
@@ -28,7 +29,7 @@ use super::{
|
||||
vector_engine_nanobanana_generate_content_url,
|
||||
},
|
||||
response::handle_vector_engine_response,
|
||||
types::{GeneratedImages, ReferenceImage, VectorEngineImageSettings},
|
||||
types::{GeneratedImages, RawImageEditOptions, ReferenceImage, VectorEngineImageSettings},
|
||||
util::truncate_raw,
|
||||
};
|
||||
|
||||
@@ -537,6 +538,34 @@ pub async fn create_vector_engine_image_edit_with_references_and_model(
|
||||
candidate_count: u32,
|
||||
reference_images: &[ReferenceImage],
|
||||
failure_context: &str,
|
||||
) -> Result<GeneratedImages, PlatformImageError> {
|
||||
create_vector_engine_image_edit_with_references_and_model_and_options(
|
||||
http_client,
|
||||
settings,
|
||||
model,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
size,
|
||||
candidate_count,
|
||||
reference_images,
|
||||
None,
|
||||
failure_context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn create_vector_engine_image_edit_with_references_and_model_and_options(
|
||||
http_client: &reqwest::Client,
|
||||
settings: &VectorEngineImageSettings,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
negative_prompt: Option<&str>,
|
||||
size: &str,
|
||||
candidate_count: u32,
|
||||
reference_images: &[ReferenceImage],
|
||||
options: Option<&RawImageEditOptions>,
|
||||
failure_context: &str,
|
||||
) -> Result<GeneratedImages, PlatformImageError> {
|
||||
let requested_model = normalize_vector_engine_image_model(model);
|
||||
if reference_images.is_empty() {
|
||||
@@ -611,19 +640,37 @@ pub async fn create_vector_engine_image_edit_with_references_and_model(
|
||||
&mut recovered_failure_audits,
|
||||
));
|
||||
};
|
||||
let response = match send_vector_engine_multipart_edit_request_with_curl(
|
||||
request_url.as_str(),
|
||||
settings.api_key.as_str(),
|
||||
upstream_model,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
normalized_size.as_str(),
|
||||
candidate_count,
|
||||
reference_images,
|
||||
attempt_timeout_ms,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let response = match match options {
|
||||
Some(options) => {
|
||||
send_vector_engine_multipart_edit_request_with_curl_options(
|
||||
request_url.as_str(),
|
||||
settings.api_key.as_str(),
|
||||
upstream_model,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
normalized_size.as_str(),
|
||||
candidate_count,
|
||||
reference_images,
|
||||
Some(options),
|
||||
attempt_timeout_ms,
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
send_vector_engine_multipart_edit_request_with_curl(
|
||||
request_url.as_str(),
|
||||
settings.api_key.as_str(),
|
||||
upstream_model,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
normalized_size.as_str(),
|
||||
candidate_count,
|
||||
reference_images,
|
||||
attempt_timeout_ms,
|
||||
)
|
||||
.await
|
||||
}
|
||||
} {
|
||||
Ok(response) => {
|
||||
if should_retry_vector_engine_upstream_response(
|
||||
response.status,
|
||||
|
||||
@@ -7,8 +7,11 @@ use curl::{
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{
|
||||
audit::build_failure_audit, constants::VECTOR_ENGINE_PROVIDER, error::PlatformImageError,
|
||||
request::build_prompt_with_negative, types::ReferenceImage,
|
||||
audit::build_failure_audit,
|
||||
constants::VECTOR_ENGINE_PROVIDER,
|
||||
error::PlatformImageError,
|
||||
request::build_prompt_with_negative,
|
||||
types::{RawImageEditOptions, ReferenceImage},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -119,6 +122,34 @@ pub(crate) async fn send_vector_engine_multipart_edit_request_with_curl(
|
||||
candidate_count: u32,
|
||||
reference_images: &[ReferenceImage],
|
||||
timeout_ms: u64,
|
||||
) -> Result<VectorEngineCurlResponse, VectorEngineCurlError> {
|
||||
send_vector_engine_multipart_edit_request_with_curl_options(
|
||||
request_url,
|
||||
api_key,
|
||||
model,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
normalized_size,
|
||||
candidate_count,
|
||||
reference_images,
|
||||
None,
|
||||
timeout_ms,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn send_vector_engine_multipart_edit_request_with_curl_options(
|
||||
request_url: &str,
|
||||
api_key: &str,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
negative_prompt: Option<&str>,
|
||||
normalized_size: &str,
|
||||
candidate_count: u32,
|
||||
reference_images: &[ReferenceImage],
|
||||
options: Option<&RawImageEditOptions>,
|
||||
timeout_ms: u64,
|
||||
) -> Result<VectorEngineCurlResponse, VectorEngineCurlError> {
|
||||
let request_url = request_url.to_string();
|
||||
let api_key = api_key.to_string();
|
||||
@@ -127,6 +158,7 @@ pub(crate) async fn send_vector_engine_multipart_edit_request_with_curl(
|
||||
let negative_prompt = negative_prompt.map(str::to_string);
|
||||
let normalized_size = normalized_size.to_string();
|
||||
let reference_images = reference_images.to_vec();
|
||||
let options = options.cloned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
send_multipart_edit_request_with_curl_blocking(
|
||||
request_url.as_str(),
|
||||
@@ -137,6 +169,7 @@ pub(crate) async fn send_vector_engine_multipart_edit_request_with_curl(
|
||||
normalized_size.as_str(),
|
||||
candidate_count,
|
||||
reference_images.as_slice(),
|
||||
options.as_ref(),
|
||||
timeout_ms,
|
||||
)
|
||||
})
|
||||
@@ -239,6 +272,7 @@ fn send_multipart_edit_request_with_curl_blocking(
|
||||
normalized_size: &str,
|
||||
candidate_count: u32,
|
||||
reference_images: &[ReferenceImage],
|
||||
options: Option<&RawImageEditOptions>,
|
||||
timeout_ms: u64,
|
||||
) -> Result<VectorEngineCurlResponse, VectorEngineCurlError> {
|
||||
let mut form = Form::new();
|
||||
@@ -253,6 +287,28 @@ fn send_multipart_edit_request_with_curl_blocking(
|
||||
.contents(normalized_size.as_bytes())
|
||||
.add()?;
|
||||
|
||||
if let Some(options) = options {
|
||||
if let Some(quality) = options.quality.as_deref() {
|
||||
form.part("quality").contents(quality.as_bytes()).add()?;
|
||||
}
|
||||
if let Some(background) = options.background.as_deref() {
|
||||
form.part("background")
|
||||
.contents(background.as_bytes())
|
||||
.add()?;
|
||||
}
|
||||
if let Some(output_format) = options.output_format.as_deref() {
|
||||
form.part("output_format")
|
||||
.contents(output_format.as_bytes())
|
||||
.add()?;
|
||||
}
|
||||
if let Some(mask) = options.mask.as_ref() {
|
||||
form.part("mask")
|
||||
.buffer(mask.file_name.as_str(), mask.bytes.clone())
|
||||
.content_type(mask.mime_type.as_str())
|
||||
.add()?;
|
||||
}
|
||||
}
|
||||
|
||||
for reference_image in reference_images {
|
||||
form.part("image")
|
||||
.buffer(
|
||||
|
||||
@@ -6,6 +6,7 @@ mod curl_transport;
|
||||
mod error;
|
||||
mod image_source;
|
||||
mod payload;
|
||||
mod raw_edit;
|
||||
mod request;
|
||||
mod response;
|
||||
mod transport;
|
||||
@@ -25,6 +26,7 @@ pub use constants::{
|
||||
};
|
||||
pub use error::{PlatformImageError, PlatformImageStatusHint};
|
||||
pub use image_source::download_remote_image;
|
||||
pub use raw_edit::create_vector_engine_raw_image_edit;
|
||||
pub use request::{
|
||||
build_vector_engine_image_request_body, build_vector_engine_image_request_body_with_model,
|
||||
build_vector_engine_nanobanana_generate_content_request_body, normalize_image_size_for_model,
|
||||
@@ -32,4 +34,7 @@ pub use request::{
|
||||
vector_engine_nanobanana_generate_content_url,
|
||||
};
|
||||
pub use transport::build_vector_engine_image_http_client;
|
||||
pub use types::{DownloadedImage, GeneratedImages, ReferenceImage, VectorEngineImageSettings};
|
||||
pub use types::{
|
||||
DownloadedImage, GeneratedImages, RawImageEditOptions, ReferenceImage,
|
||||
VectorEngineImageSettings,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use super::{
|
||||
client::create_vector_engine_image_edit_with_references_and_model_and_options,
|
||||
constants::GPT_IMAGE_2_MODEL,
|
||||
error::PlatformImageError,
|
||||
types::{GeneratedImages, RawImageEditOptions, ReferenceImage, VectorEngineImageSettings},
|
||||
};
|
||||
|
||||
/// Sends the raw GPT Image 2 edit contract while keeping VectorEngine's
|
||||
/// multipart transport inside this crate.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn create_vector_engine_raw_image_edit(
|
||||
http_client: &reqwest::Client,
|
||||
settings: &VectorEngineImageSettings,
|
||||
prompt: &str,
|
||||
image: &ReferenceImage,
|
||||
options: RawImageEditOptions,
|
||||
failure_context: &str,
|
||||
) -> Result<GeneratedImages, PlatformImageError> {
|
||||
let size = format!("{}x{}", options.width, options.height);
|
||||
create_vector_engine_image_edit_with_references_and_model_and_options(
|
||||
http_client,
|
||||
settings,
|
||||
GPT_IMAGE_2_MODEL,
|
||||
prompt,
|
||||
None,
|
||||
size.as_str(),
|
||||
1,
|
||||
std::slice::from_ref(image),
|
||||
Some(&options),
|
||||
failure_context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -29,3 +29,15 @@ pub struct ReferenceImage {
|
||||
pub mime_type: String,
|
||||
pub file_name: String,
|
||||
}
|
||||
|
||||
/// Raw GPT Image 2 edit options. The API layer owns validation; this type only
|
||||
/// carries values that must be forwarded to VectorEngine.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RawImageEditOptions {
|
||||
pub quality: Option<String>,
|
||||
pub background: Option<String>,
|
||||
pub output_format: Option<String>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub mask: Option<ReferenceImage>,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user