pwish-cli 0.0.0-stage → 0.1.1

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.
package/src/suite.js ADDED
@@ -0,0 +1,129 @@
1
+ import { dimensionFor, SIZE_TO_QUALITY, SUITE_SITES, SUITE_SCENES, resolveModel } from "./models.js";
2
+ import { uploadFiles } from "./upload.js";
3
+ import { pollTask, createConversation, waitForTasks, imagesOf } from "./tasks.js";
4
+
5
+ /**
6
+ * 套图第一步:让 AI 根据商品图 + 卖点,为每个场景写提示词。
7
+ * POST tasks/login/suite/prompt → { data.task_id } → GET tasks/login/suite/prompt/{task_id}
8
+ */
9
+ export async function planSuitePrompts(client, { resourceIds, sellingPoints, site = "amazon", country, lang, scenes, size = "1:1" }) {
10
+ const siteInfo = SUITE_SITES[site] || SUITE_SITES.amazon;
11
+ const body = {
12
+ from: "suite-prompt",
13
+ selling_points: sellingPoints,
14
+ site,
15
+ country: country || siteInfo.country,
16
+ lang: lang || siteInfo.lang,
17
+ scene: scenes,
18
+ size,
19
+ source_resource_ids: resourceIds,
20
+ };
21
+ const res = await client.request("tasks/login/suite/prompt", { method: "POST", body, timeout: 90_000 });
22
+ const taskId = res.data?.task_id;
23
+ if (!taskId) throw new Error("AI 写卖点失败:接口未返回 task_id");
24
+ const data = await pollTask(client, async () => {
25
+ const r = await client.request(`tasks/login/suite/prompt/${taskId}`, { timeout: 60_000 });
26
+ return r.data;
27
+ }, { timeoutMs: 300_000, intervalMs: 2500 });
28
+ return { taskId, prompts: data.prompts || {}, raw: data };
29
+ }
30
+
31
+ /**
32
+ * 套图第二步:按场景批量出图。
33
+ * POST tasks/login/suite → { data.task_id } → GET tasks/login/suite/{task_id}
34
+ */
35
+ export async function generateSuite(client, {
36
+ resourceIds,
37
+ sellingPoints,
38
+ prompts = {},
39
+ scenes,
40
+ site = "amazon",
41
+ country,
42
+ lang,
43
+ model = "gemini-3",
44
+ sizeName = "2K",
45
+ ratio = "1:1",
46
+ pattern = "economy",
47
+ conversationId,
48
+ timeoutMs = 900_000,
49
+ onProgress,
50
+ }) {
51
+ const siteInfo = SUITE_SITES[site] || SUITE_SITES.amazon;
52
+ const m = resolveModel(model);
53
+ const quality = SIZE_TO_QUALITY[sizeName] || "high";
54
+ const cid = conversationId || (await createConversation(client)).conversation_id;
55
+
56
+ const body = {
57
+ from: "design-suite",
58
+ selling_points: sellingPoints,
59
+ filter_keywords: "",
60
+ site,
61
+ country: country || siteInfo.country,
62
+ lang: lang || siteInfo.lang,
63
+ scene: scenes,
64
+ model_type: m.id,
65
+ size: ratio,
66
+ quality,
67
+ pattern,
68
+ source_resource_ids: resourceIds,
69
+ prompts,
70
+ conversation_id: cid,
71
+ };
72
+ if (m.family === "gpt2") {
73
+ body.resolution = quality;
74
+ body.dimension = dimensionFor(ratio === "auto" ? "1:1" : ratio, sizeName);
75
+ }
76
+
77
+ const res = await client.request("tasks/login/suite", { method: "POST", body, timeout: 120_000 });
78
+ const taskId = res.data?.task_id;
79
+ if (!taskId) throw new Error(`套图任务创建失败:${JSON.stringify(res).slice(0, 200)}`);
80
+
81
+ const data = await pollTask(client, async () => {
82
+ const r = await client.request(`tasks/login/suite/${taskId}`, { timeout: 60_000 });
83
+ return r.data;
84
+ }, { timeoutMs, intervalMs: 4000, onProgress: (p) => onProgress?.({ ...p, taskId }) });
85
+
86
+ return { conversationId: cid, taskId, raw: data };
87
+ }
88
+
89
+ /** 从套图任务结果里抽出 { scene: [images] } */
90
+ export function suiteImagesOf(data) {
91
+ const out = {};
92
+ const push = (scene, item) => {
93
+ const imgs = imagesOf(item);
94
+ if (!imgs.length) return;
95
+ const key = scene || "unknown";
96
+ out[key] = [...(out[key] || []), ...imgs];
97
+ };
98
+
99
+ // 主流结构:data.items = { main: { answer: [...] }, selling: {...} }
100
+ const items = data?.items;
101
+ if (items && typeof items === "object" && !Array.isArray(items)) {
102
+ for (const [scene, item] of Object.entries(items)) {
103
+ if (item && (item.answer || item.file)) push(scene, item);
104
+ }
105
+ if (Object.keys(out).length) return out;
106
+ }
107
+
108
+ const walk = (node, scene) => {
109
+ if (!node || typeof node !== "object") return;
110
+ if (Array.isArray(node)) {
111
+ for (const n of node) walk(n, scene);
112
+ return;
113
+ }
114
+ const s = node.scene || node.promptKey || scene;
115
+ if (Array.isArray(node.answer) || node.file || node.url) push(s, node);
116
+ for (const key of ["suiteItems", "answers", "data", "list"]) {
117
+ if (node[key]) walk(node[key], s);
118
+ }
119
+ };
120
+ walk(data, null);
121
+
122
+ if (!Object.keys(out).length) {
123
+ const imgs = imagesOf(data);
124
+ if (imgs.length) out.unknown = imgs;
125
+ }
126
+ return out;
127
+ }
128
+
129
+ export { SUITE_SCENES, SUITE_SITES, waitForTasks, uploadFiles };
package/src/tasks.js ADDED
@@ -0,0 +1,154 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { ApiError } from "./api.js";
4
+
5
+ /** 轮询直到任务完成;返回后端最终 data。 */
6
+ export async function pollTask(client, fetcher, { timeoutMs = 300_000, intervalMs = 3000, onProgress } = {}) {
7
+ const started = Date.now();
8
+ let last = null;
9
+ let missCount = 0;
10
+ while (Date.now() - started < timeoutMs) {
11
+ const data = await fetcher();
12
+ if (!data) {
13
+ missCount += 1;
14
+ if (missCount > 10) throw new Error("任务查询连续失败,已放弃");
15
+ } else {
16
+ missCount = 0;
17
+ last = data;
18
+ const state = Number(data.state ?? data.status ?? 0);
19
+ const progress = Number(data.progress ?? 0);
20
+ onProgress?.({ state, progress, data });
21
+ if (state === 1 || progress === 100) return data;
22
+ if (state < 0) {
23
+ throw new Error(`任务失败(state=${state})${data.error ? `:${data.error}` : ""}`);
24
+ }
25
+ }
26
+ await new Promise((r) => setTimeout(r, intervalMs));
27
+ }
28
+ if (last && (Number(last.state) === 1 || Number(last.progress) === 100)) return last;
29
+ throw new Error(`等待超时(${Math.round(timeoutMs / 1000)}s)。任务可能仍在服务端排队,稍后用 \`pwish task <task_id>\` 查询。`);
30
+ }
31
+
32
+ export async function createConversation(client) {
33
+ const res = await client.request("image/conversations", { method: "POST", body: {} });
34
+ return res.data;
35
+ }
36
+
37
+ export async function createImageMessage(client, payload) {
38
+ const res = await client.request("tasks/login/image-messages", { method: "POST", body: payload, timeout: 90_000 });
39
+ const data = res.data || {};
40
+ const taskId = data.task_id || data.message_id;
41
+ if (!taskId) throw new Error("创建任务失败:接口未返回 task_id");
42
+ return { ...data, task_id: taskId, message_id: data.message_id || taskId };
43
+ }
44
+
45
+ /** 批量查询任务:返回 { [task_id]: data } */
46
+ export async function batchTasks(client, taskIds) {
47
+ if (!taskIds.length) return {};
48
+ const res = await client.request("tasks/login/image-messages/batch", {
49
+ query: { task_ids: taskIds.join(",") },
50
+ timeout: 60_000,
51
+ });
52
+ const items = res.data?.items;
53
+ if (items && typeof items === "object") return items;
54
+ const list = Array.isArray(res.data) ? res.data : [];
55
+ const map = {};
56
+ for (const item of list) {
57
+ const id = item.task_id || item.message_id;
58
+ if (id) map[id] = item;
59
+ }
60
+ return map;
61
+ }
62
+
63
+ export async function waitForTasks(client, taskIds, { timeoutMs = 300_000, intervalMs = 3000, onProgress } = {}) {
64
+ const done = new Map();
65
+ const started = Date.now();
66
+ while (Date.now() - started < timeoutMs) {
67
+ const map = await batchTasks(client, taskIds.filter((id) => !done.has(id)));
68
+ for (const id of taskIds) {
69
+ const item = map[id];
70
+ if (!item || done.has(id)) continue;
71
+ const state = Number(item.state ?? item.status ?? 0);
72
+ const progress = Number(item.progress ?? 0);
73
+ const hasAnswer = Array.isArray(item.answer) && item.answer.length > 0;
74
+ onProgress?.({ taskId: id, state, progress, item });
75
+ if (state === 1 || (progress === 100 && hasAnswer)) done.set(id, item);
76
+ else if (state < 0) done.set(id, { ...item, failed: true });
77
+ }
78
+ if (done.size === taskIds.length) break;
79
+ await new Promise((r) => setTimeout(r, intervalMs));
80
+ }
81
+ for (const id of taskIds) if (!done.has(id)) done.set(id, { task_id: id, failed: true, timeout: true });
82
+ return done;
83
+ }
84
+
85
+ export function imagesOf(item) {
86
+ const answers = item?.answer;
87
+ if (!Array.isArray(answers)) return [];
88
+ return answers
89
+ .flatMap((a) => (Array.isArray(a) ? a : [a]))
90
+ .map((a) => ({
91
+ url: a?.file || a?.url,
92
+ thumb: a?.thumbnail,
93
+ fileId: a?.file_id,
94
+ isVideo: Boolean(a?.video || a?.is_video),
95
+ }))
96
+ .filter((a) => a.url);
97
+ }
98
+
99
+ function extFromUrl(url, fallback) {
100
+ try {
101
+ const p = new URL(url).pathname;
102
+ const ext = path.extname(p).toLowerCase();
103
+ if (ext && ext.length <= 6) return ext;
104
+ } catch {
105
+ /* ignore */
106
+ }
107
+ return fallback;
108
+ }
109
+
110
+ export async function downloadImage(url, outDir, basename, fallbackExt = ".png") {
111
+ fs.mkdirSync(outDir, { recursive: true });
112
+ const ext = extFromUrl(url, fallbackExt);
113
+ const file = path.join(outDir, `${basename}${ext}`);
114
+ const res = await fetch(url);
115
+ if (!res.ok) throw new Error(`下载失败 HTTP ${res.status}:${url.slice(0, 120)}`);
116
+ const buf = Buffer.from(await res.arrayBuffer());
117
+ fs.writeFileSync(file, buf);
118
+ return { file, bytes: buf.length };
119
+ }
120
+
121
+ export async function listConversations(client, { page = 1, perPage = 20 } = {}) {
122
+ const res = await client.request("image/conversations", { query: { page, per_page: perPage } });
123
+ return res.data;
124
+ }
125
+
126
+ export async function getConversation(client, conversationId, { page = 1, perPage = 50 } = {}) {
127
+ const res = await client.request(`image/conversations/${conversationId}`, { query: { page, per_page: perPage } });
128
+ return res.data;
129
+ }
130
+
131
+ export async function queueStatus(client) {
132
+ const res = await client.request("image/conversations/task-queue");
133
+ return res.data;
134
+ }
135
+
136
+ /**
137
+ * 校验 token 是否真实有效。
138
+ * 注意:vips/all-free-counts 对无效 token 也会返回 200,不能用来判断登录态,
139
+ * 因此这里用会返回 401 的会话列表接口做探针。
140
+ */
141
+ export async function verifyToken(client) {
142
+ const res = await client.request("image/conversations", { query: { page: 1, per_page: 1 } });
143
+ if (res?.status && res.status !== 200) {
144
+ throw new ApiError("token 无效或已过期,请重新登录", { code: "UNAUTHORIZED", payload: res });
145
+ }
146
+ return true;
147
+ }
148
+
149
+ export async function freeCounts(client, cfg) {
150
+ const res = await client.request("vips/all-free-counts", {
151
+ query: { website: cfg?.language === "zh" ? "zh" : "en" },
152
+ });
153
+ return res.data;
154
+ }
package/src/upload.js ADDED
@@ -0,0 +1,112 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const MIME = {
6
+ ".png": "image/png",
7
+ ".jpg": "image/jpeg",
8
+ ".jpeg": "image/jpeg",
9
+ ".webp": "image/webp",
10
+ ".gif": "image/gif",
11
+ ".bmp": "image/bmp",
12
+ ".avif": "image/avif",
13
+ ".heic": "image/heic",
14
+ };
15
+
16
+ export function mimeOf(file) {
17
+ return MIME[path.extname(file).toLowerCase()] || "application/octet-stream";
18
+ }
19
+
20
+ function ossV1Signature({ verb, contentMd5 = "", mime, date, ossHeaders, bucket, key, secret }) {
21
+ const canonicalHeaders = Object.entries(ossHeaders)
22
+ .map(([k, v]) => [k.toLowerCase(), v])
23
+ .sort(([a], [b]) => (a > b ? 1 : a < b ? -1 : 0))
24
+ .map(([k, v]) => `${k}:${v}\n`)
25
+ .join("");
26
+ const stringToSign = `${verb}\n${contentMd5}\n${mime}\n${date}\n${canonicalHeaders}/${bucket}/${key}`;
27
+ return crypto.createHmac("sha1", secret).update(stringToSign).digest("base64");
28
+ }
29
+
30
+ /**
31
+ * 上传本地文件到 picwish 的 OSS,返回 resource_id(后续作为 source_resource_ids 传给生成接口)。
32
+ * 流程:POST authorizations/oss 拿 STS → PUT 到 OSS(带 x-oss-callback,由服务端回调登记资源)。
33
+ */
34
+ export async function uploadFile(client, file, prefix = "pub/tasks/input/llm_chats") {
35
+ const abs = path.resolve(file);
36
+ const stat = fs.statSync(abs);
37
+ if (!stat.isFile()) throw new Error(`不是文件:${abs}`);
38
+ if (stat.size > 20 * 1024 * 1024) throw new Error(`文件超过 20MB:${abs}`);
39
+
40
+ const name = path.basename(abs);
41
+ const body = fs.readFileSync(abs);
42
+ const mime = mimeOf(abs);
43
+
44
+ const auth = await client.request("authorizations/oss", {
45
+ method: "POST",
46
+ body: { filenames: [name], object_prefix: prefix },
47
+ });
48
+ const data = auth.data;
49
+ const key = data.objects?.[name];
50
+ if (!key) throw new Error(`上传授权未返回 object key:${JSON.stringify(data).slice(0, 200)}`);
51
+
52
+ const host = `${data.bucket}.${data.endpoint}`;
53
+ const date = new Date().toUTCString();
54
+ const callback = data.callback
55
+ ? Buffer.from(
56
+ JSON.stringify({
57
+ callbackUrl: encodeURI(data.callback.url),
58
+ callbackBody: data.callback.body,
59
+ callbackHost: host,
60
+ callbackBodyType: data.callback.type,
61
+ }),
62
+ ).toString("base64")
63
+ : "";
64
+
65
+ const ossHeaders = {
66
+ "x-oss-date": date,
67
+ ...(callback ? { "x-oss-callback": callback } : {}),
68
+ "x-oss-security-token": data.credential.security_token,
69
+ };
70
+
71
+ const signature = ossV1Signature({
72
+ verb: "PUT",
73
+ mime,
74
+ date,
75
+ ossHeaders,
76
+ bucket: data.bucket,
77
+ key,
78
+ secret: data.credential.access_key_secret,
79
+ });
80
+
81
+ const res = await fetch(`https://${host}/${key}`, {
82
+ method: "PUT",
83
+ headers: {
84
+ "Content-Type": mime,
85
+ Authorization: `OSS ${data.credential.access_key_id}:${signature}`,
86
+ ...ossHeaders,
87
+ },
88
+ body,
89
+ });
90
+ const text = await res.text();
91
+ if (!res.ok) {
92
+ throw new Error(`OSS 上传失败 HTTP ${res.status}:${text.slice(0, 300)}`);
93
+ }
94
+
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(text);
98
+ } catch {
99
+ throw new Error(`OSS 回调返回非 JSON:${text.slice(0, 200)}`);
100
+ }
101
+ const info = parsed.data || {};
102
+ if (!info.resource_id) throw new Error(`OSS 回调未返回 resource_id:${text.slice(0, 200)}`);
103
+ return { resourceId: info.resource_id, key, url: info.url, width: info.width, height: info.height, name };
104
+ }
105
+
106
+ export async function uploadFiles(client, files, prefix) {
107
+ const out = [];
108
+ for (const f of files) {
109
+ out.push(await uploadFile(client, f, prefix));
110
+ }
111
+ return out;
112
+ }