110 lines
6.8 KiB
JavaScript
110 lines
6.8 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 { execFileSync } from 'node:child_process'
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
|
|
import { tmpdir } from 'node:os'
|
|
import { join, resolve } from 'node:path'
|
|
|
|
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
|
|
|
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'))
|
|
spec.items = defs.map((g) => ({ id: g.code, motif: 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
|
|
}
|
|
const prompt = band.prompt
|
|
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
|
|
const task = [
|
|
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
|
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
|
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
|
|
'',
|
|
prompt,
|
|
].join('\n')
|
|
console.log(`${band.id}: Codex로 그리는 중…`)
|
|
try {
|
|
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
|
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', task], { stdio: ['ignore', 'ignore', 'inherit'] })
|
|
} catch (e) {
|
|
rmSync(work, { recursive: true, force: true })
|
|
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
|
}
|
|
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
|
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
|
|
if (!png) {
|
|
console.error(`${band.id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
|
|
failed.push(band.id)
|
|
continue
|
|
}
|
|
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath(band.id)])
|
|
rmSync(work, { recursive: true, force: true })
|
|
console.log(`${band.id}: ${outPath(band.id)}`)
|
|
}
|
|
|
|
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)
|