@kevlns/art-workshop 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { openaiImagesAdapter } from "./openai-images.mjs";
1
2
  import { dashscopeAdapter } from "./dashscope.mjs";
2
3
  export function createAdapterRegistry(entries) {
3
4
  const registry = new Map();
@@ -25,4 +26,4 @@ export function createAdapterRegistry(entries) {
25
26
  },
26
27
  });
27
28
  }
28
- export const adapters = createAdapterRegistry([dashscopeAdapter]);
29
+ export const adapters = createAdapterRegistry([dashscopeAdapter, openaiImagesAdapter]);
@@ -0,0 +1,49 @@
1
+ import {readFile,stat} from 'node:fs/promises';
2
+ import sharp from 'sharp';
3
+ import {RemoteError,requestJson} from '../transport/http.mjs';
4
+
5
+ function fields(request) {
6
+ const body = {model:request.model,prompt:request.prompt,size:request.size.replace('*','x'),n:request.count,output_format:'png'};
7
+ if (request.parameters.quality) body.quality=request.parameters.quality;
8
+ return body;
9
+ }
10
+ const endpointPath = request => request.images.length ? '/images/edits' : '/images/generations';
11
+ export const openaiImagesAdapter = {
12
+ id:'openai-images',label:'OpenAI Images',version:1,cancellation:'unsupported',
13
+ preview:request=>({...fields(request), ...(request.images.length ? {image:request.images} : {})}),
14
+ commandPreview:request=>['POST','/v1'+endpointPath(request)],
15
+ async prepare(request,context) {
16
+ const config=JSON.parse(process.env.ART_IMAGE_CONNECTION || '{}'), key=process.env.ART_IMAGE_KEY;
17
+ if (config.api !== 'openai-images' || !key) throw Error('OpenAI Images 连接或凭据未配置');
18
+ const base=new URL(config.baseUrl);
19
+ if (base.protocol !== 'https:' || base.username || base.password || base.search || base.hash) throw Error('图片接口地址无效');
20
+ const endpoint=base.href.replace(/\/$/,'');
21
+ if(context.baseUrl && context.baseUrl.replace(/\/$/,'')!==endpoint) throw Error('图片连接地址与冻结请求不同');
22
+ const url=endpoint+(/\/v1$/.test(endpoint)?'':'/v1')+endpointPath(request);
23
+ const headers={Authorization:'Bearer '+key};
24
+ let body=fields(request);
25
+ if(request.images.length) {
26
+ const form=new FormData();
27
+ for(const [field,value] of Object.entries(body)) form.set(field,String(value));
28
+ for(const [index,file] of request.images.entries()) {
29
+ if ((await stat(file)).size > request.inputPolicy.maxBytes) throw Error('参考图片过大');
30
+ const bytes=await readFile(file), {format}=await sharp(bytes).metadata();
31
+ if(!request.inputPolicy.formats.includes(format)) throw Error('参考图片格式不受支持');
32
+ form.append(request.images.length === 1 ? 'image' : 'image[]',new Blob([bytes],{type:'image/'+format}),`reference-${index+1}.${format}`);
33
+ }
34
+ body=form;
35
+ } else headers['Content-Type']='application/json';
36
+ return {endpoint,url,headers,body};
37
+ },
38
+ async submit(request,context) {
39
+ const {url,headers,body}=context.prepared;
40
+ const result=await requestJson(url,{...context,method:'POST',headers,body,timeout:request.transport.timeoutMilliseconds,maxResponseBytes:128*1024*1024});
41
+ if (!Array.isArray(result.data) || result.data.length !== request.count) throw new RemoteError('图片结果数量无效',{unsettled:true});
42
+ if (result.data.every(item=>typeof item?.b64_json==='string' && item.b64_json.length>0))
43
+ return {state:'completed',inline:result.data.map(item=>Buffer.from(item.b64_json,'base64'))};
44
+ if (result.data.every(item=>{try {const u=new URL(item.url);return u.protocol==='https:'&&!u.username&&!u.password;} catch{return false;}}))
45
+ return {state:'completed',urls:result.data.map(item=>item.url)};
46
+ throw new RemoteError('图片响应缺少有效产物',{unsettled:true});
47
+ },
48
+ async query(){throw Error('同步图片请求没有远端任务 ID');}
49
+ };
@@ -1,10 +1,40 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { readFile, writeFile, mkdir, link, rm } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import sharp from "sharp";
5
5
  import { hash } from "../shared.mjs";
6
6
  import { boundedBody, RemoteError } from "../transport/http.mjs";
7
+ const imageDigest = buffer => createHash("sha256").update(buffer).digest("hex");
7
8
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9
+ async function writeImage(buffer,index,context) {
10
+ const info = await sharp(buffer, {
11
+ limitInputPixels: 64 * 1024 * 1024,
12
+ }).metadata();
13
+ if (!["png", "jpeg", "webp"].includes(info.format))
14
+ throw new Error("生成产物不是可支持的图片格式");
15
+ const file =
16
+ context.prefix +
17
+ (index ? "--" + (index + 1) : "") +
18
+ "." +
19
+ (info.format === "jpeg" ? "jpg" : info.format),
20
+ path = join(context.outputDir, file);
21
+ const temporary = path + ".tmp-" + randomUUID();
22
+ try {
23
+ await writeFile(temporary, buffer, { flag: "wx" });
24
+ try {
25
+ await link(temporary, path);
26
+ } catch (error) {
27
+ if (
28
+ error.code !== "EEXIST" ||
29
+ imageDigest(await readFile(path)) !== imageDigest(buffer)
30
+ )
31
+ throw error;
32
+ }
33
+ } finally {
34
+ await rm(temporary, { force: true });
35
+ }
36
+ return file;
37
+ }
8
38
  async function download(receipt, context) {
9
39
  if (!context.outputDir) return { urls: receipt.urls };
10
40
  if (!/^[a-zA-Z0-9_.-]+$/.test(context.prefix))
@@ -32,33 +62,8 @@ async function download(receipt, context) {
32
62
  clearTimeout(timeout);
33
63
  clearInterval(timer);
34
64
  }
35
- const info = await sharp(buffer, {
36
- limitInputPixels: 64 * 1024 * 1024,
37
- }).metadata();
38
- if (!["png", "jpeg", "webp"].includes(info.format))
39
- throw new Error("生成产物不是可支持的图片格式");
40
- const file =
41
- context.prefix +
42
- (index ? "--" + (index + 1) : "") +
43
- "." +
44
- (info.format === "jpeg" ? "jpg" : info.format),
45
- path = join(context.outputDir, file);
46
- const temporary = path + ".tmp-" + randomUUID();
47
- try {
48
- await writeFile(temporary, buffer, { flag: "wx" });
49
- try {
50
- await link(temporary, path);
51
- } catch (error) {
52
- if (
53
- error.code !== "EEXIST" ||
54
- hash(await readFile(path)) !== hash(buffer)
55
- )
56
- throw error;
57
- }
58
- } finally {
59
- await rm(temporary, { force: true });
60
- }
61
- files.push(file);
65
+ files.push(await writeImage(buffer,index,context));
66
+
62
67
  }
63
68
  return { files, urls: receipt.urls };
64
69
  }
@@ -114,7 +119,19 @@ export async function executeRemote(request, adapter, context = {}) {
114
119
  baseUrl,
115
120
  prepared,
116
121
  });
117
- await persist(submitted);
122
+ if (submitted.inline) {
123
+ if (!context.outputDir || !/^[a-zA-Z0-9_.-]+$/.test(context.prefix) || submitted.inline.length !== request.count)
124
+ throw new RemoteError("同步图片交付参数或数量无效", {unsettled:true});
125
+ try {
126
+ await mkdir(context.outputDir,{recursive:true});
127
+ const localImages = [];
128
+ for (const [index,buffer] of submitted.inline.entries())
129
+ localImages.push({file:await writeImage(buffer,index,context),sha256:imageDigest(buffer)});
130
+ await persist({state:"completed",localImages});
131
+ } catch {
132
+ throw new RemoteError("图片服务已返回,原请求的本地文件或回执未能保存",{unsettled:true});
133
+ }
134
+ } else await persist(submitted);
118
135
  }
119
136
  while (receipt.state === "accepted") {
120
137
  if (cancelled())
@@ -133,6 +150,17 @@ export async function executeRemote(request, adapter, context = {}) {
133
150
  ? "upstream_cancelled"
134
151
  : "upstream_failed",
135
152
  });
153
+ if (receipt.state === "completed" && receipt.localImages) {
154
+ if (!context.outputDir || !/^[a-zA-Z0-9_.-]+$/.test(context.prefix) || receipt.localImages.length !== request.count) throw new Error("本地图片回执无效");
155
+ const files = [];
156
+ for (const [index,image] of receipt.localImages.entries()) {
157
+ const prefix = context.prefix + (index ? "--" + (index + 1) : "");
158
+ if (!["png","jpg","webp"].some(ext=>image.file === prefix+"."+ext) ||
159
+ imageDigest(await readFile(join(context.outputDir,image.file))) !== image.sha256) throw new Error("本地图片完整性校验失败");
160
+ files.push(image.file);
161
+ }
162
+ return {files,urls:[]};
163
+ }
136
164
  if (
137
165
  receipt.state !== "completed" ||
138
166
  !Array.isArray(receipt.urls) ||
@@ -278,6 +278,17 @@ const recorded = [
278
278
 
279
279
  export const modelDefinitions = [
280
280
  ...profiles.map((p) => ({ ...p, supported: true })),
281
+ {
282
+ supported: true, id: "openai-gpt-image-2.5-v1", api: "openai-images",
283
+ models: ["gpt-image-2.5-flare", "gpt-image-2.5-sunburst"],
284
+ input: ["text", "image"], output: ["image"], modes: ["generate", "edit"],
285
+ inputPolicy: {maxBytes: 50 * 1024 * 1024, formats: ["png","webp","jpeg"]},
286
+ transport: {adapter:"openai-images",version:1,mode:"sync",timeoutMilliseconds:1800000},
287
+ fields: {quality:{type:"string",wire:"quality",enum:["auto","low","medium","high"]}},
288
+ maxImages:16,maxCount:1,maxSeed:2147483647,negativeInPrompt:true,
289
+ dimensions:{min:16,max:3840,step:16,minArea:655360,maxArea:8294400,minRatio:1/3,maxRatio:3},
290
+ notes:["支持文生图与多图编辑;模型不接收 seed。"],source:"https://developers.openai.com/api/docs/guides/image-generation"
291
+ },
281
292
  ...recorded.map((p) => ({
282
293
  ...p,
283
294
  api: "dashscope",
@@ -36,6 +36,7 @@ export async function requestJson(
36
36
  cancelled = () => false,
37
37
  transport = fetch,
38
38
  timeout = 60000,
39
+ maxResponseBytes = 4 * 1024 * 1024,
39
40
  } = {},
40
41
  ) {
41
42
  const controller = new AbortController(),
@@ -49,7 +50,7 @@ export async function requestJson(
49
50
  headers,
50
51
  redirect: "error",
51
52
  signal: controller.signal,
52
- ...(body ? { body: JSON.stringify(body) } : {}),
53
+ ...(body ? { body: body instanceof FormData ? body : JSON.stringify(body) } : {}),
53
54
  });
54
55
  if (!response.ok)
55
56
  throw new RemoteError(
@@ -59,7 +60,7 @@ export async function requestJson(
59
60
  let result;
60
61
  try {
61
62
  result = JSON.parse(
62
- (await boundedBody(response, 4 * 1024 * 1024)).toString("utf8"),
63
+ (await boundedBody(response, maxResponseBytes)).toString("utf8"),
63
64
  );
64
65
  } catch (error) {
65
66
  if (error instanceof RemoteError) throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevlns/art-workshop",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "private": false,
5
5
  "description": "统一管理图片工坊与视频工坊:项目风格、图片生成编辑、剧本镜头、视频生成与成片精修。",
6
6
  "type": "module",