Files

89 lines
5.1 KiB
JavaScript

// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { drawWithCodex } from './codex-image.mjs'
function fail(message) {
console.error(message)
process.exit(1)
}
const args = process.argv.slice(2)
const force = args.includes('--force')
const [kind, target, ...more] = args.filter((a) => !a.startsWith('--'))
const styleFilter = more[0]
const promptFile = resolve(`image-prompts/${kind}.json`)
if (!kind || !target || !existsSync(promptFile)) fail('사용: npm run gen-image -- <ootd|tarot> <id|missing> [--force]')
const spec = JSON.parse(readFileSync(promptFile, 'utf8'))
// 각 카드는 그림 목록을 따로 적지 않고 서비스의 각 목록에서 만든다
if (spec.deck === 'gak') {
const defs = JSON.parse(readFileSync(resolve('../backend/seed/index_definition.json'), 'utf8'))
const money = JSON.parse(readFileSync(resolve('money-deck.json'), 'utf8')).cards
spec.items = [...defs, ...money].map((g) => ({ id: g.code, motif: (g.scene ?? spec.scene).replaceAll('{name}', g.name).replaceAll('{meaning}', g.description), name: g.name, meaning: g.description }))
}
const outDir = resolve(`src/assets/${kind}`)
mkdirSync(outDir, { recursive: true })
const outPath = (id) => join(outDir, `${id}.webp`)
// 그림 한 장 = { id, 프롬프트 }. ootd 는 구간 × 스타일 × 사람 × (옷 4개 | 겉옷까지 5개, id 끝에 -outer), tarot 은 주제 꾸밈(skin)마다
const jobs = spec.bands
? spec.bands.flatMap((b) =>
Object.entries(b.outfits).flatMap(([style, byPersona]) =>
Object.entries(byPersona).flatMap(([persona, outfit]) =>
[false, true].map((withOuter) => ({
id: `${b.id}-${persona}-${style}${withOuter ? '-outer' : ''}`,
band: b.id,
style,
prompt: spec.style
.replace('{items}', withOuter ? `${outfit.items}, (5) ${spec.outers?.[outfit.outer] ?? outfit.outer} as the outer layer` : outfit.items)
.replace('{count}', withOuter ? 'five' : 'four')
// 카드 이름표 자리(1 왼쪽 위·2 오른쪽 위·3 왼쪽 아래·4 오른쪽 아래·5 위 가운데)와 그림 위치를 맞춘다
.replace(
'{layout}',
withOuter
? 'top row from left to right: (1), then (5) the outer layer in the top center, then (2); bottom row: (3) bottom-left and (4) bottom-right. Five clearly separate spots, nothing else in the top center.'
: 'a 2x2 grid: (1) top-left, (2) top-right, (3) bottom-left, (4) bottom-right.',
)
.replace('{persona}', spec.personas[persona].prompt)
.replace('{style}', spec.styles[style].prompt)
.replace('{trend}', spec.styles[style].trends?.[persona] ?? '')
.replace('{layering}', b.layering ?? ''),
})),
),
),
)
: spec.items.map((it) => ({
id: it.id,
band: it.id,
prompt: spec.style.replace('{motif}', it.motif).replace('{scene}', it.motif).replaceAll('{name}', it.name ?? '').replaceAll('{meaning}', it.meaning ?? '').replace('{card}', it.card ?? ''),
}))
// 카드에 필요한 그림만: 정확한 id 를 여러 개 받거나(npm run card·관리자 서버가 씀), 구간·스타일로 좁힌다
const exact = [target, ...more].filter((t) => jobs.some((j) => j.id === t))
const picked =
exact.length > 0 ? jobs.filter((j) => exact.includes(j.id))
: target === 'missing' ? jobs.filter((j) => !existsSync(outPath(j.id)))
: jobs.filter((j) => j.id === target || j.band === target || j.style === target)
const bands = exact.length === 0 && styleFilter ? picked.filter((j) => j.style === styleFilter) : picked
if (bands.length === 0) fail(target === 'missing' ? '빠진 그림이 없어요.' : `'${target}' 은 ${promptFile} 에 없어요.${spec.bands ? ` 구간: ${spec.bands.map((b) => b.id).join(', ')} / 스타일: ${Object.keys(spec.styles).join(', ')} / 사람: ${Object.keys(spec.personas).join(', ')}` : ` id: ${spec.items.map((i) => i.id).join(', ')}`}`)
const failed = []
for (const band of bands) {
if (existsSync(outPath(band.id)) && !force) {
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
continue
}
let result
try {
result = drawWithCodex({ id: band.id, prompt: band.prompt, outPath: outPath(band.id) })
} catch (e) {
fail(e.message)
}
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
if (result !== 'ok') failed.push(band.id)
}
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)