merge: promote AI render material signed urls
This commit is contained in:
commit
fce3f46a04
@ -79,7 +79,7 @@ export const config = {
|
||||
filePath: process.env.QINIU_FILE_PATH,
|
||||
useHttps: process.env.QINIU_USE_HTTPS !== 'false',
|
||||
privateBucket: process.env.QINIU_PRIVATE_BUCKET === 'true',
|
||||
privateUrlExpiresSeconds: Number(process.env.QINIU_PRIVATE_URL_EXPIRES_SECONDS || 3600),
|
||||
privateUrlExpiresSeconds: Number(process.env.QINIU_PRIVATE_URL_EXPIRES_SECONDS || 7200),
|
||||
},
|
||||
auth: {
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
|
||||
@ -262,36 +262,44 @@ describe('storage object provider', () => {
|
||||
data: {},
|
||||
})
|
||||
|
||||
const storage = await import('./storage')
|
||||
const buffer = Buffer.from('private-glb')
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
|
||||
|
||||
await expect(
|
||||
storage.uploadBufferToObjectStorage(
|
||||
buffer,
|
||||
'/models/table.glb',
|
||||
'model/gltf-binary',
|
||||
),
|
||||
).resolves.toBe(
|
||||
'/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb',
|
||||
)
|
||||
try {
|
||||
const storage = await import('./storage')
|
||||
const buffer = Buffer.from('private-glb')
|
||||
|
||||
expect(storage.getStorageAccessMode()).toBe('private')
|
||||
expect(storage.createObjectReadUrl('models/table.glb')).toContain(
|
||||
'http://tevepd6od.hd-bkt.clouddn.com/prod-assets/models/table.glb?e=',
|
||||
)
|
||||
expect(
|
||||
storage.resolveObjectStorageUrlForServerAccess(
|
||||
await expect(
|
||||
storage.uploadBufferToObjectStorage(
|
||||
buffer,
|
||||
'/models/table.glb',
|
||||
'model/gltf-binary',
|
||||
),
|
||||
).resolves.toBe(
|
||||
'/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb',
|
||||
),
|
||||
).toContain(
|
||||
'http://tevepd6od.hd-bkt.clouddn.com/prod-assets/models/table.glb?e=',
|
||||
)
|
||||
expect(
|
||||
storage.resolveObjectStorageUrlForClientAccess(
|
||||
'/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb',
|
||||
),
|
||||
).toBe('/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb')
|
||||
expect(mockQiniuPrivateDownloadUrl).not.toHaveBeenCalled()
|
||||
)
|
||||
|
||||
expect(storage.getStorageAccessMode()).toBe('private')
|
||||
const signedReadUrl = storage.createObjectReadUrl('models/table.glb')
|
||||
expect(signedReadUrl).toContain(
|
||||
'http://tevepd6od.hd-bkt.clouddn.com/prod-assets/models/table.glb?e=',
|
||||
)
|
||||
expect(signedReadUrl).toContain('?e=1700007200&token=')
|
||||
expect(
|
||||
storage.resolveObjectStorageUrlForServerAccess(
|
||||
'/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb',
|
||||
),
|
||||
).toContain(
|
||||
'http://tevepd6od.hd-bkt.clouddn.com/prod-assets/models/table.glb?e=',
|
||||
)
|
||||
expect(
|
||||
storage.resolveObjectStorageUrlForClientAccess(
|
||||
'/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb',
|
||||
),
|
||||
).toBe('/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb')
|
||||
expect(mockQiniuPrivateDownloadUrl).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
nowSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('returns direct HTTPS Qiniu read URLs to clients for non-protected assets', async () => {
|
||||
@ -315,6 +323,18 @@ describe('storage object provider', () => {
|
||||
'https://qnycdn.example.com/prod-assets/models/table.glb?e=123&token=abc',
|
||||
),
|
||||
).toBe('/api/storage/object?key=prod-assets%2Fmodels%2Ftable.glb')
|
||||
expect(
|
||||
storage.readObjectStorageKeyFromUrl(
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=123&token=abc',
|
||||
),
|
||||
).toBe('prod-assets/materials/textures/material-library/oak.webp')
|
||||
expect(
|
||||
storage.resolveObjectStorageUrlForServerAccess(
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=123&token=abc',
|
||||
),
|
||||
).toContain(
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns direct HTTPS Qiniu read URLs for legacy material routes', async () => {
|
||||
|
||||
@ -484,7 +484,7 @@ function createQiniuStorageAdapter(): ObjectStorageAdapter {
|
||||
const useHttps = readBooleanEnv(process.env.QINIU_USE_HTTPS, true)
|
||||
const privateBucket = readBooleanEnv(process.env.QINIU_PRIVATE_BUCKET, false)
|
||||
const privateUrlExpiresSeconds = Math.max(
|
||||
Number(process.env.QINIU_PRIVATE_URL_EXPIRES_SECONDS) || 3600,
|
||||
Number(process.env.QINIU_PRIVATE_URL_EXPIRES_SECONDS) || 7200,
|
||||
60,
|
||||
)
|
||||
|
||||
|
||||
@ -0,0 +1,176 @@
|
||||
import { afterAll, beforeEach, describe, expect, it, jest } from '@jest/globals'
|
||||
import { AssistedAssemblyAiRenderStatus } from '@prisma/client'
|
||||
|
||||
const originalFetch = global.fetch
|
||||
|
||||
const mockAssistedAssemblyAiRenderCreate = jest.fn()
|
||||
const mockUploadBufferToS3 = jest.fn()
|
||||
const mockReadObjectStorageKeyFromUrl = jest.fn()
|
||||
const mockCreateObjectReadUrl = jest.fn()
|
||||
const mockGetExternalImageApiConfig = jest.fn()
|
||||
const mockCallExternalImageGenerateApi = jest.fn()
|
||||
|
||||
function createMockRecord(data: Record<string, unknown>) {
|
||||
return {
|
||||
id: 'render-1',
|
||||
prompt: data.prompt,
|
||||
negativePrompt: data.negativePrompt ?? null,
|
||||
params: data.params,
|
||||
referenceImageUrl: data.referenceImageUrl ?? null,
|
||||
resultImages: data.resultImages ?? [],
|
||||
workspaceSnapshot: data.workspaceSnapshot,
|
||||
assetSnapshot: data.assetSnapshot,
|
||||
externalRequestId: data.externalRequestId ?? null,
|
||||
attempts: data.attempts ?? [],
|
||||
status: data.status,
|
||||
errorMessage: data.errorMessage ?? null,
|
||||
durationMs: data.durationMs ?? null,
|
||||
createdAt: new Date('2026-06-16T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-06-16T00:00:00.000Z'),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadService() {
|
||||
jest.doMock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
assistedAssemblyAiRender: {
|
||||
create: mockAssistedAssemblyAiRenderCreate,
|
||||
findMany: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
jest.doMock('@/lib/storage', () => ({
|
||||
uploadBufferToS3: mockUploadBufferToS3,
|
||||
createObjectReadUrl: mockCreateObjectReadUrl,
|
||||
readObjectStorageKeyFromUrl: mockReadObjectStorageKeyFromUrl,
|
||||
}))
|
||||
|
||||
jest.doMock('../external-image-generate.service', () => ({
|
||||
getExternalImageApiConfig: mockGetExternalImageApiConfig,
|
||||
callExternalImageGenerateApi: mockCallExternalImageGenerateApi,
|
||||
}))
|
||||
|
||||
return import('../assisted-assembly-ai-render.service')
|
||||
}
|
||||
|
||||
describe('assistedAssemblyAiRenderService.create', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules()
|
||||
jest.clearAllMocks()
|
||||
global.fetch = originalFetch
|
||||
mockAssistedAssemblyAiRenderCreate.mockImplementation(async (args: { data: Record<string, unknown> }) =>
|
||||
createMockRecord(args.data),
|
||||
)
|
||||
mockUploadBufferToS3.mockResolvedValue('/api/storage/object?key=ai-reference.png' as never)
|
||||
mockCreateObjectReadUrl.mockImplementation((key: string) =>
|
||||
`https://qnycdn.example.com/${key}?e=fresh&token=fresh`,
|
||||
)
|
||||
mockGetExternalImageApiConfig.mockResolvedValue({
|
||||
enabled: true,
|
||||
baseUrl: 'https://ai.example.com',
|
||||
apiKey: 'ai-key',
|
||||
} as never)
|
||||
mockCallExternalImageGenerateApi.mockResolvedValue({
|
||||
requestId: 'external-req-1',
|
||||
model: null,
|
||||
images: [{ originalUrl: 'https://cdn.example.com/render.png' }],
|
||||
generatedImageIds: [],
|
||||
generatedAssetIds: [],
|
||||
attempts: [],
|
||||
} as never)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
it('resigns stored material texture URLs and sends one deduplicated image URL', async () => {
|
||||
const staleTextureUrlA =
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=old&token=a'
|
||||
const staleTextureUrlB =
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=old&token=b'
|
||||
const freshTextureUrl =
|
||||
'https://qnycdn.example.com/prod-assets/materials/textures/material-library/oak.webp?e=fresh&token=fresh'
|
||||
const fetchMock = jest.fn()
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
|
||||
mockReadObjectStorageKeyFromUrl.mockImplementation((value: string) =>
|
||||
value.includes('/oak.webp')
|
||||
? 'prod-assets/materials/textures/material-library/oak.webp'
|
||||
: null,
|
||||
)
|
||||
mockCreateObjectReadUrl.mockReturnValue(freshTextureUrl)
|
||||
|
||||
const { assistedAssemblyAiRenderService } = await loadService()
|
||||
|
||||
const result = await assistedAssemblyAiRenderService.create(
|
||||
{
|
||||
prompt: '生成白底产品图',
|
||||
imageCount: 1,
|
||||
aspectRatio: '1:1',
|
||||
imageSize: '2K',
|
||||
referenceImageDataUrl: `data:image/png;base64,${Buffer.from([9, 8, 7]).toString('base64')}`,
|
||||
workspaceSnapshot: { selectedNodeIds: ['top', 'drawer'] },
|
||||
assetSnapshot: {
|
||||
nodes: [
|
||||
{
|
||||
id: 'top',
|
||||
name: '桌面',
|
||||
materialConfig: {
|
||||
id: 'mat-top',
|
||||
name: '橡木',
|
||||
textureUrl: staleTextureUrlA,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'drawer',
|
||||
name: '抽屉面',
|
||||
materialConfig: {
|
||||
id: 'mat-drawer',
|
||||
name: '橡木抽屉',
|
||||
textureUrl: staleTextureUrlB,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{ id: 'user-1' } as never,
|
||||
)
|
||||
|
||||
expect(result.status).toBe(AssistedAssemblyAiRenderStatus.SUCCEEDED)
|
||||
expect(mockCreateObjectReadUrl).toHaveBeenCalledTimes(1)
|
||||
expect(mockCreateObjectReadUrl).toHaveBeenCalledWith(
|
||||
'prod-assets/materials/textures/material-library/oak.webp',
|
||||
)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
|
||||
const externalInput = mockCallExternalImageGenerateApi.mock.calls[0]?.[0] as {
|
||||
prompt: string
|
||||
referenceImageUrls?: string[]
|
||||
additionalReferenceImages?: unknown[]
|
||||
}
|
||||
expect(externalInput.prompt).toContain('Material mapping for this product')
|
||||
expect(externalInput.prompt).toContain('"桌面"')
|
||||
expect(externalInput.prompt).toContain('"抽屉面"')
|
||||
expect(externalInput.referenceImageUrls).toEqual([freshTextureUrl])
|
||||
expect(externalInput.additionalReferenceImages).toBeUndefined()
|
||||
|
||||
const createArgs = mockAssistedAssemblyAiRenderCreate.mock.calls.at(-1)?.[0] as {
|
||||
data: { params: unknown }
|
||||
}
|
||||
expect(createArgs.data.params).toEqual({
|
||||
imageCount: 1,
|
||||
aspectRatio: '1:1',
|
||||
imageSize: '2K',
|
||||
materialReferences: {
|
||||
extracted: 1,
|
||||
urlReferenced: 1,
|
||||
fileUploaded: 0,
|
||||
deliveryMode: 'signed-url',
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -111,4 +111,40 @@ describe("callExternalImageGenerateApi", () => {
|
||||
});
|
||||
expect(requestInit.body).toBeInstanceOf(FormData);
|
||||
});
|
||||
|
||||
it("sends file uploads and image URLs together in multipart mode", async () => {
|
||||
mockedFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
requestId: "req-3",
|
||||
images: [{ originalUrl: "https://cdn.example.com/generated-3.png" }],
|
||||
},
|
||||
}),
|
||||
} as never);
|
||||
|
||||
await callExternalImageGenerateApi({
|
||||
prompt: "test prompt",
|
||||
imageCount: 1,
|
||||
aspectRatio: "1:1",
|
||||
imageSize: "2K",
|
||||
referenceImage: {
|
||||
buffer: Buffer.from([1, 2, 3]),
|
||||
contentType: "image/png",
|
||||
fileName: "source.png",
|
||||
},
|
||||
referenceImageUrls: [
|
||||
"https://qnycdn.example.com/prod/materials/oak.webp?e=fresh&token=fresh",
|
||||
],
|
||||
});
|
||||
|
||||
const [, requestInit] = mockedFetch.mock.calls[0] as [string, RequestInit];
|
||||
expect(requestInit.body).toBeInstanceOf(FormData);
|
||||
const formData = requestInit.body as FormData;
|
||||
expect(formData.get("prompt")).toBe("test prompt");
|
||||
expect(formData.get("imageUrls")).toBe(
|
||||
"https://qnycdn.example.com/prod/materials/oak.webp?e=fresh&token=fresh",
|
||||
);
|
||||
expect(formData.getAll("images")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@ -2,7 +2,11 @@ import type { Prisma } from '@prisma/client'
|
||||
import { AssistedAssemblyAiRenderStatus } from '@prisma/client'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { uploadBufferToS3 } from '@/lib/storage'
|
||||
import {
|
||||
createObjectReadUrl,
|
||||
readObjectStorageKeyFromUrl,
|
||||
uploadBufferToS3,
|
||||
} from '@/lib/storage'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
@ -20,10 +24,25 @@ const MAX_MATERIAL_TEXTURES = 6
|
||||
interface MaterialTextureEntry {
|
||||
materialId: string
|
||||
materialName: string
|
||||
textureUrl: string
|
||||
textureKey: string
|
||||
nodeNames: string[]
|
||||
}
|
||||
|
||||
function readTextureStorageKey(textureUrl: string): string | null {
|
||||
try {
|
||||
return readObjectStorageKeyFromUrl(textureUrl)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function appendDistinctText(target: string[], value: string | null | undefined): void {
|
||||
const normalized = trimToNull(value)
|
||||
if (normalized && !target.includes(normalized)) {
|
||||
target.push(normalized)
|
||||
}
|
||||
}
|
||||
|
||||
function extractMaterialTexturesFromSnapshot(assetSnapshot: unknown): MaterialTextureEntry[] {
|
||||
const snapshot = toRecord(assetSnapshot)
|
||||
const nodes = Array.isArray(snapshot.nodes) ? snapshot.nodes : []
|
||||
@ -34,21 +53,26 @@ function extractMaterialTexturesFromSnapshot(assetSnapshot: unknown): MaterialTe
|
||||
for (const rawNode of nodes) {
|
||||
const node = toRecord(rawNode)
|
||||
const mc = toRecord(node.materialConfig)
|
||||
const materialId = typeof mc.id === 'string' ? mc.id : null
|
||||
const textureUrl = typeof mc.textureUrl === 'string' ? mc.textureUrl : null
|
||||
const materialName = typeof mc.name === 'string' ? mc.name : null
|
||||
const textureUrl = trimToNull(typeof mc.textureUrl === 'string' ? mc.textureUrl : null)
|
||||
const nodeName = typeof node.name === 'string' ? node.name : null
|
||||
|
||||
if (!materialId || !textureUrl) continue
|
||||
if (!textureUrl) continue
|
||||
|
||||
const existing = materialMap.get(materialId)
|
||||
const textureKey = readTextureStorageKey(textureUrl)
|
||||
if (!textureKey) continue
|
||||
|
||||
const dedupeKey = `storage:${textureKey}`
|
||||
const materialId = trimToNull(typeof mc.id === 'string' ? mc.id : null) ?? dedupeKey
|
||||
const materialName = trimToNull(typeof mc.name === 'string' ? mc.name : null) ?? materialId
|
||||
|
||||
const existing = materialMap.get(dedupeKey)
|
||||
if (existing) {
|
||||
if (nodeName) existing.nodeNames.push(nodeName)
|
||||
appendDistinctText(existing.nodeNames, nodeName)
|
||||
} else {
|
||||
materialMap.set(materialId, {
|
||||
materialMap.set(dedupeKey, {
|
||||
materialId,
|
||||
materialName: materialName ?? materialId,
|
||||
textureUrl,
|
||||
materialName,
|
||||
textureKey,
|
||||
nodeNames: nodeName ? [nodeName] : [],
|
||||
})
|
||||
}
|
||||
@ -70,22 +94,16 @@ function buildMaterialMappingPromptSuffix(entries: MaterialTextureEntry[]): stri
|
||||
return `\n\nMaterial mapping for this product (each attached texture reference is labeled):\n${lines.join('\n')}\nApply each material texture to its corresponding part as shown in the reference image.`
|
||||
}
|
||||
|
||||
async function downloadTextureBuffer(url: string): Promise<{ buffer: Buffer; contentType: string } | null> {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
|
||||
const contentType = response.headers.get('content-type') ?? 'image/jpeg'
|
||||
const arrayBuffer = await response.arrayBuffer()
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
if (buffer.length === 0 || buffer.length > 8 * 1024 * 1024) return null
|
||||
|
||||
return { buffer, contentType: contentType.split(';')[0]!.trim() }
|
||||
} catch {
|
||||
return null
|
||||
function buildMaterialReferenceImageUrls(entries: MaterialTextureEntry[]): string[] {
|
||||
const urls: string[] = []
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
urls.push(createObjectReadUrl(entry.textureKey))
|
||||
} catch {
|
||||
// Keep AI rendering usable if one material reference cannot be signed.
|
||||
}
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
export interface AssistedAssemblyAiRenderDTO {
|
||||
@ -198,6 +216,30 @@ function normalizeShortOption(value: unknown, fallback: string, fieldLabel: stri
|
||||
return normalized
|
||||
}
|
||||
|
||||
function buildAiRenderParams(params: {
|
||||
imageCount: number
|
||||
aspectRatio: string
|
||||
imageSize: string
|
||||
materialReferences: {
|
||||
extracted: number
|
||||
urlReferenced: number
|
||||
fileUploaded: number
|
||||
deliveryMode: 'signed-url'
|
||||
}
|
||||
}): Prisma.InputJsonValue {
|
||||
return {
|
||||
imageCount: params.imageCount,
|
||||
aspectRatio: params.aspectRatio,
|
||||
imageSize: params.imageSize,
|
||||
materialReferences: {
|
||||
extracted: params.materialReferences.extracted,
|
||||
urlReferenced: params.materialReferences.urlReferenced,
|
||||
fileUploaded: params.materialReferences.fileUploaded,
|
||||
deliveryMode: params.materialReferences.deliveryMode,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function decodeReferenceImageDataUrl(value: unknown): { buffer: Buffer; contentType: string; extension: string } {
|
||||
if (typeof value !== 'string') {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '缺少当前 3D 预览截图')
|
||||
@ -372,11 +414,19 @@ export class AssistedAssemblyAiRenderService {
|
||||
const aspectRatio = normalizeShortOption(input.aspectRatio, '16:9', '宽高比')
|
||||
const imageSize = normalizeShortOption(input.imageSize, '2K', '图片规格')
|
||||
const referenceImage = decodeReferenceImageDataUrl(input.referenceImageDataUrl)
|
||||
const params = {
|
||||
const materialEntries = extractMaterialTexturesFromSnapshot(input.assetSnapshot)
|
||||
const materialReferenceStats = {
|
||||
extracted: materialEntries.length,
|
||||
urlReferenced: 0,
|
||||
fileUploaded: 0,
|
||||
deliveryMode: 'signed-url' as const,
|
||||
}
|
||||
const buildCurrentParams = () => buildAiRenderParams({
|
||||
imageCount,
|
||||
aspectRatio,
|
||||
imageSize,
|
||||
}
|
||||
materialReferences: materialReferenceStats,
|
||||
})
|
||||
|
||||
const storageKey = `assisted-assembly/ai-renders/${createdBy}/${Date.now()}-${nanoid(8)}.${referenceImage.extension}`
|
||||
const referenceImageUrl = await uploadBufferToS3(referenceImage.buffer, storageKey, referenceImage.contentType)
|
||||
@ -384,7 +434,7 @@ export class AssistedAssemblyAiRenderService {
|
||||
const baseCreateData = {
|
||||
prompt,
|
||||
negativePrompt,
|
||||
params: params as Prisma.InputJsonValue,
|
||||
params: buildCurrentParams(),
|
||||
referenceImageUrl,
|
||||
resultImages: [] as unknown as Prisma.InputJsonValue,
|
||||
createdBy,
|
||||
@ -398,6 +448,7 @@ export class AssistedAssemblyAiRenderService {
|
||||
const record = await prisma.assistedAssemblyAiRender.create({
|
||||
data: {
|
||||
...baseCreateData,
|
||||
params: buildCurrentParams(),
|
||||
status: AssistedAssemblyAiRenderStatus.FAILED,
|
||||
errorMessage: '辅助装配 AI 生图服务未启用或未配置',
|
||||
durationMs: Date.now() - startedAt,
|
||||
@ -407,29 +458,12 @@ export class AssistedAssemblyAiRenderService {
|
||||
}
|
||||
|
||||
try {
|
||||
// 提取材质贴图信息
|
||||
const materialEntries = extractMaterialTexturesFromSnapshot(input.assetSnapshot)
|
||||
// 生成材质映射提示词
|
||||
const materialSuffix = buildMaterialMappingPromptSuffix(materialEntries)
|
||||
const enhancedPrompt = materialSuffix ? `${prompt}${materialSuffix}` : prompt
|
||||
|
||||
// 下载材质贴图
|
||||
const additionalReferenceImages: Array<{ buffer: Buffer; contentType: string; fileName: string }> = []
|
||||
if (materialEntries.length > 0) {
|
||||
const downloadResults = await Promise.allSettled(
|
||||
materialEntries.map((entry) => downloadTextureBuffer(entry.textureUrl)),
|
||||
)
|
||||
for (let i = 0; i < downloadResults.length; i++) {
|
||||
const result = downloadResults[i]!
|
||||
if (result.status === 'fulfilled' && result.value) {
|
||||
const ext = result.value.contentType.includes('png') ? 'png' : 'jpg'
|
||||
additionalReferenceImages.push({
|
||||
buffer: result.value.buffer,
|
||||
contentType: result.value.contentType,
|
||||
fileName: `material-${materialEntries[i]!.materialName.replace(/[^a-zA-Z0-9\u4e00-\u9fff]+/g, '-')}.${ext}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
const materialReferenceImageUrls = buildMaterialReferenceImageUrls(materialEntries)
|
||||
materialReferenceStats.urlReferenced = materialReferenceImageUrls.length
|
||||
|
||||
const result = await callExternalImageGenerateApi({
|
||||
prompt: enhancedPrompt,
|
||||
@ -441,7 +475,7 @@ export class AssistedAssemblyAiRenderService {
|
||||
...referenceImage,
|
||||
fileName: `assembly-reference.${referenceImage.extension}`,
|
||||
},
|
||||
additionalReferenceImages: additionalReferenceImages.length > 0 ? additionalReferenceImages : undefined,
|
||||
referenceImageUrls: materialReferenceImageUrls.length > 0 ? materialReferenceImageUrls : undefined,
|
||||
disabledMessage: '辅助装配 AI 生图服务未启用或未配置',
|
||||
})
|
||||
|
||||
@ -453,6 +487,7 @@ export class AssistedAssemblyAiRenderService {
|
||||
const record = await prisma.assistedAssemblyAiRender.create({
|
||||
data: {
|
||||
...baseCreateData,
|
||||
params: buildCurrentParams(),
|
||||
status,
|
||||
externalRequestId: result.requestId,
|
||||
resultImages: result.images as unknown as Prisma.InputJsonValue,
|
||||
@ -467,6 +502,7 @@ export class AssistedAssemblyAiRenderService {
|
||||
const record = await prisma.assistedAssemblyAiRender.create({
|
||||
data: {
|
||||
...baseCreateData,
|
||||
params: buildCurrentParams(),
|
||||
status: AssistedAssemblyAiRenderStatus.FAILED,
|
||||
errorMessage: error instanceof Error ? error.message : 'AI 生图失败',
|
||||
durationMs: Date.now() - startedAt,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user