Files

47 lines
3.1 KiB
JavaScript

// Codex CLI의 이미지 생성 도구로 그림 한 장을 만들어 webp 로 저장한다. gen-image.mjs(고정 데이터 그림)와 daily-ootd.mjs(그날 코디 그림)가 같이 쓴다.
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { cli, toWebp } from './bin.mjs'
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
export const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
/**
* @param {{ id: string, prompt: string, outPath: string, images?: string[], log?: (s: string) => void }} job
* images: 참고 사진(그 옷·색을 따라 그리게 할 때). 결과는 outPath(webp, 가로 1024).
* @returns {'ok' | 'not-saved'} 실패(한도·로그인)는 throw
*/
export function drawWithCodex({ id, prompt, outPath, images = [], log = console.log }) {
const work = mkdtempSync(join(tmpdir(), `gen-${id}-`))
const task = [
images.length
? '첨부한 참고 사진(코디 사진·상품 사진)의 옷·색·소재·실루엣을 그대로 따르되, 아래 프롬프트의 스타일로 새 그림을 내장 이미지 생성 도구로 만든다 (사진을 복사하지 말고, 사람은 절대 그리지 않는다).'
: '내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
'통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.',
'',
prompt,
].join('\n')
log(`${id}: Codex로 그리는 중…${images.length ? ` (참고 사진 ${images.length}장)` : ''}`)
try {
// -i 는 파일을 여러 개 받아서 뒤의 프롬프트까지 파일로 읽는다 → 프롬프트는 stdin 으로 준다
const imageArgs = images.flatMap((p) => ['-i', p])
const [codex, ...pre] = cli('codex')
execFileSync(codex, [...pre, 'exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', ...imageArgs], { input: task, stdio: ['pipe', 'ignore', 'inherit'] })
} catch (e) {
rmSync(work, { recursive: true, force: true })
throw new Error(`${id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
}
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
if (!png) {
log(`${id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
return 'not-saved'
}
toWebp(join(work, png), outPath)
rmSync(work, { recursive: true, force: true })
log(`${id}: ${outPath}`)
return 'ok'
}