167 lines
8.3 KiB
JavaScript
167 lines
8.3 KiB
JavaScript
// 인스타 카드를 템플릿대로 JPEG로 만든다. 웹 화면(/render)을 헤드리스 Chrome으로 찍는다.
|
|
// 사용: npm run card -- <tarot|ootd> [--topic 주제] [--feedback 피드백] [--copy <웹 화면 '대화로 만들기'의 값>] [--out <폴더>]
|
|
// --topic·--feedback 이 있으면 Claude가 먼저 문구를 기획하고(관리자 서버 /api/plan), 기획안을 출력한 뒤 그 문구로 그린다.
|
|
// 날씨 타로는 --copy 가 없으면 주제 없이도 Claude가 기획한다. --color <테마>로 색을 고르고, 없으면 무작위.
|
|
// 그리기 전에 그날 카드에 없는 그림만 Codex로 만든다 (--no-images 로 건너뜀).
|
|
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
|
|
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
|
|
import { execFileSync } from 'node:child_process'
|
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
import { resolve } from 'node:path'
|
|
import { CHROME, toJpeg } from './bin.mjs'
|
|
|
|
const SLIDES = { tarot: 5, ootd: 4, intro: 8, foliage: 5 }
|
|
// 기본 문구가 서비스 데이터 그대로라 Claude 기획이 꼭 필요한 템플릿 (src/cards/templates.tsx autoPlan)
|
|
const AUTO_PLAN = ['tarot']
|
|
// src/cards/themes.ts THEMES 의 id
|
|
const THEMES = ['sunset', 'sky', 'mint', 'berry', 'lemon', 'lavender']
|
|
const ADMIN_URL = process.env.ADMIN_URL ?? 'http://localhost:5175'
|
|
const API_URL = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
|
|
|
function fail(message) {
|
|
console.error(message)
|
|
process.exit(1)
|
|
}
|
|
|
|
const args = process.argv.slice(2)
|
|
const flag = (name) => {
|
|
const i = args.indexOf(name)
|
|
if (i < 0) return null
|
|
const [, value] = args.splice(i, 2)
|
|
return value
|
|
}
|
|
let copy = flag('--copy')
|
|
const topic = flag('--topic')
|
|
const feedback = flag('--feedback')
|
|
const color = flag('--color')
|
|
const styleArg = flag('--style')
|
|
const outArg = flag('--out')
|
|
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
|
|
let noImages = take('--no-images')
|
|
const postNow = take('--post')
|
|
const postWait = take('--post-wait')
|
|
// --daily: 코디를 고정 데이터 대신 그날 무신사 인기 스냅에서 뽑아 그린다 (scripts/daily-ootd.mjs)
|
|
const daily = take('--daily')
|
|
const [template] = args
|
|
|
|
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
|
|
if (color && !THEMES.includes(color)) fail(`색은 ${THEMES.join(', ')} 중 하나예요.`)
|
|
if (/[\\/]/.test(CHROME) && !existsSync(CHROME)) fail(`Chrome을 찾지 못했어요: ${CHROME}\nCHROME_PATH 환경변수로 경로를 알려 주세요.`)
|
|
|
|
await fetch(`${API_URL}/v1/region/list`).catch((e) => fail(`날씨각 API(${API_URL})에 연결하지 못했어요. 백엔드가 켜져 있는지 확인하세요. (${e.message})`))
|
|
await fetch(ADMIN_URL).catch(() => fail(`관리자 화면(${ADMIN_URL})이 꺼져 있어요. admin 폴더에서 npm run dev 를 먼저 켜 주세요.`))
|
|
|
|
const decode = (value) => (value ? JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) : {})
|
|
if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template))) {
|
|
const current = decode(copy)
|
|
console.log('Claude가 기획하는 중…')
|
|
const res = await fetch(`${ADMIN_URL}/api/plan`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ template, topic: topic ?? '', feedback: feedback ?? '', current }),
|
|
})
|
|
const body = await res.json()
|
|
if (!res.ok) fail(`기획하지 못했어요: ${body.error}`)
|
|
console.log(`주제: ${body.topic}`)
|
|
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
|
|
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
|
|
// 타로: 오늘 고른 각을 적어 두면 다음 7일은 다른 각이 나온다 (scripts/plan.mjs recentCodes)
|
|
if (template === 'tarot') {
|
|
const file = resolve('out/tarot-history.json')
|
|
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
|
const history = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}
|
|
const codes = ['c1', 'c2', 'c3'].map((k) => body.copy[k]).filter(Boolean)
|
|
history[today] = [...new Set([...(history[today] ?? []), ...codes])]
|
|
mkdirSync(resolve('out'), { recursive: true })
|
|
writeFileSync(file, JSON.stringify(history, null, 1))
|
|
}
|
|
}
|
|
|
|
{
|
|
const current = decode(copy)
|
|
const theme = color ?? current.theme ?? THEMES[Math.floor(Math.random() * THEMES.length)]
|
|
copy = Buffer.from(JSON.stringify({ ...current, theme })).toString('base64url')
|
|
console.log(`색: ${theme}`)
|
|
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
|
|
}
|
|
|
|
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
|
const outDir = resolve(outArg ?? `out/${day}`)
|
|
|
|
if (daily) {
|
|
if (template !== 'ootd') fail('--daily 는 ootd 템플릿에서만 써요.')
|
|
const { runDailyOotd, toCardOutfits } = await import('./daily-ootd.mjs')
|
|
// 포스트 하나는 스타일 하나: --style <casual|semi|formal|street|minimal>, 없으면 --copy 의 style, 그것도 없으면 꾸안꾸
|
|
const style = styleArg ?? decode(copy).style ?? 'minimal'
|
|
const { outfits } = await runDailyOotd({ outDir, style })
|
|
copy = Buffer.from(JSON.stringify({ ...decode(copy), style, outfits: JSON.stringify(toCardOutfits(outfits)) })).toString('base64url')
|
|
noImages = true
|
|
}
|
|
|
|
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
|
|
if (!noImages) {
|
|
const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ template, copy: decode(copy) }),
|
|
}).then((r) => r.json())
|
|
if (start.error) fail(`그림을 만들지 못했어요: ${start.error}`)
|
|
if (start.status === 'running') {
|
|
console.log(`그림 ${start.total}장 만드는 중 (Codex, 한 장에 1~2분)…`)
|
|
let state = start
|
|
while (state.status === 'running') {
|
|
await new Promise((r) => setTimeout(r, 5000))
|
|
state = await fetch(`${ADMIN_URL}/api/gen-image`).then((r) => r.json())
|
|
}
|
|
for (const line of state.log) console.log(` ${line}`)
|
|
if (state.status === 'failed') console.log('일부 그림을 못 만들어 그 장은 아이콘·옷 이름으로 나가요.')
|
|
// 새 그림이 화면에 반영될 시간
|
|
await new Promise((r) => setTimeout(r, 3000))
|
|
}
|
|
}
|
|
|
|
mkdirSync(outDir, { recursive: true })
|
|
|
|
const files = []
|
|
for (let slide = 1; slide <= SLIDES[template]; slide++) {
|
|
const query = new URLSearchParams({ template, slide: String(slide) })
|
|
if (copy) query.set('copy', copy)
|
|
const png = resolve(outDir, `${day}_${template}_${slide}.png`)
|
|
const jpg = png.replace(/\.png$/, '.jpg')
|
|
const shot = [
|
|
'--headless=new',
|
|
'--disable-gpu',
|
|
'--hide-scrollbars',
|
|
'--force-device-scale-factor=1',
|
|
'--window-size=1080,1350',
|
|
'--virtual-time-budget=20000',
|
|
`--screenshot=${png}`,
|
|
`${ADMIN_URL}/render?${query}`,
|
|
]
|
|
// 크롬이 한 장에서 멈추는 일이 있어 45초 넘으면 끊고 그 장만 한 번 더 찍는다
|
|
try {
|
|
execFileSync(CHROME, shot, { stdio: 'ignore', timeout: 45_000 })
|
|
} catch {
|
|
console.log(`${slide}번째 장이 45초 넘게 멈춰 다시 찍어요`)
|
|
execFileSync(CHROME, shot, { stdio: 'ignore', timeout: 45_000 })
|
|
}
|
|
toJpeg(png, jpg)
|
|
rmSync(png)
|
|
files.push(jpg)
|
|
}
|
|
|
|
console.log(`${template} · ${files.length}장`)
|
|
for (const f of files) console.log(f)
|
|
|
|
if (postNow || postWait) {
|
|
const images = files.map((f) => readFileSync(f).toString('base64'))
|
|
const res = await fetch(`${ADMIN_URL}/api/post`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ template, texts: decode(copy), images, publish: postNow }),
|
|
})
|
|
const body = await res.json()
|
|
if (!res.ok || body.result?.success === false) fail(`날씨각에 올리지 못했어요: ${body.error ?? body.result?.desc}`)
|
|
console.log(postNow ? `날씨각 오늘 피드에 올렸어요: 카드 ${body.card_id}, 포스트 ${body.post_id}` : `승인 대기로 저장했어요: 카드 ${body.card_id}`)
|
|
}
|