Files

107 lines
6.8 KiB
JavaScript

// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { drawWithCodex } from './codex-image.mjs'
import { extractOutfit } from './outfit.mjs'
import { pickSnaps } from './snap.mjs'
const API_URL = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
const REGION = '1114000000' // 서울 중구 (src/cards/data.ts BASE_REGION)
const spec = JSON.parse(readFileSync(resolve('image-prompts/ootd.json'), 'utf8'))
const PERSONA_ORDER = ['f20', 'm20', 'f40', 'm40']
const COUNT_WORD = { 3: 'three', 4: 'four', 5: 'five' }
/** 오늘 예보 → 아침·낮 기온, 기온 구간 (src/cards/data.ts temps 와 같은 계산) */
export async function weatherToday() {
const res = await fetch(`${API_URL}/v1/weather/today?region=${REGION}`)
const d = await res.json()
if (d.result?.success === false || !d.slots?.length) throw new Error(`오늘 예보를 받지 못했어요 (${d.result?.desc ?? '응답 없음'})`)
const hour = (s) => new Date(s.at).getHours()
const withTemp = d.slots.filter((s) => s.temp_c != null)
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
const t = day.length ? day : withTemp
const maxC = Math.round(Math.max(...t.map((s) => s.temp_c)))
const morning = t.find((s) => hour(s) === 6) ?? t[0]
const morningC = Math.round(morning.temp_c)
// 낮 최고만 보면 아침·저녁 추위를 놓친다: 아침 체감과 낮 최고의 평균으로 구간을 정한다
const feelC = ((morning.feels_c ?? morning.temp_c) + maxC) / 2
const band = spec.bands.find((b) => feelC >= b.from) ?? spec.bands[spec.bands.length - 1]
return { day: d.day, morningC, maxC, band: band.id, layering: band.layering ?? '' }
}
// 카드 이름표 순서(상의·겉옷·하의·신발·가방)와 그림 번호 순서(1 상의·2 하의·3 신발·4 가방·5 겉옷)는 다르다
const LABEL_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
const DRAW_ORDER = ['top', 'bottom', 'shoes', 'bag', 'outer']
function layoutFor(slots) {
const has = (s) => slots.includes(s)
const topRow = has('outer') ? '(1) top-left, the outer layer in the top center, (2) top-right' : '(1) top-left, (2) top-right'
const bottomRow = has('bag') ? '(3) bottom-left and (4) bottom-right' : '(3) bottom-center'
return `top row: ${topRow}; bottom row: ${bottomRow}. Clearly separate spots, nothing else in between.`
}
export function buildPrompt(persona, outfit, weather) {
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
const drawn = DRAW_ORDER.filter((s) => by[s])
const items = drawn.map((s, i) => `(${i + 1}) ${by[s].prompt}${s === 'outer' ? ' as the outer layer' : ''}`).join(', ')
return spec.style
.replace('{items}', items)
.replace('{count}', COUNT_WORD[drawn.length] ?? String(drawn.length))
.replace('{layout}', layoutFor(drawn))
.replace('{persona}', spec.personas[persona].prompt)
.replace('{style}', outfit.style)
.replace('{trend}', 'follow the attached reference photos (the outfit photo and the product thumbnails): the same garments, colors, materials and silhouettes')
.replace('{layering}', weather.layering)
}
/** 포스트 하나는 스타일 하나(기본 꾸안꾸). 네 사람 모두 그 스타일 스냅에서 고르고 제목도 같은 스타일로 간다.
* @returns {Promise<{ weather: object, outfits: { persona: string, label: string, style: string, labels: string[], image: string, source: string, items: object[] }[] }>} */
export async function runDailyOotd({ outDir, style = 'minimal', log = console.log }) {
if (!spec.styles[style]) throw new Error(`스타일은 ${Object.keys(spec.styles).join(', ')} 중 하나예요: ${style}`)
const styleLabel = spec.styles[style].label
const weather = await weatherToday()
log(`오늘 ${weather.day}: 아침 ${weather.morningC}° · 낮 ${weather.maxC}° → 구간 ${weather.band} · 스타일 ${styleLabel}`)
mkdirSync(outDir, { recursive: true })
// 사용자가 먼저 확인한 코디(snap.mjs 가 쓴 picks.json)가 있으면 다시 고르지 않고 그대로 그린다
const picksFile = join(outDir, 'snaps', 'picks.json')
const picks = existsSync(picksFile) ? JSON.parse(readFileSync(picksFile, 'utf8')) : await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
const dailyDir = resolve('public/daily')
mkdirSync(dailyDir, { recursive: true })
const outfits = []
for (const persona of PERSONA_ORDER) {
const pick = picks[persona]
log(`${persona}: Claude가 옷 목록을 뽑는 중… (${pick.url})`)
const outfit = await extractOutfit(pick, persona, weather)
// 제목은 Claude 가 본 분위기가 아니라 포스트 스타일로 통일한다
outfit.style = styleLabel
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
const labels = LABEL_ORDER.filter((s) => by[s]).map((s) => by[s].label)
log(` ${outfit.style}: ${labels.join(' · ')}`)
const id = `${weather.day}-${persona}`
const outPath = join(dailyDir, `${id}.webp`)
const images = [pick.files.image, ...pick.files.thumbs.slice(0, 4).map((t) => t.path)]
const prompt = buildPrompt(persona, outfit, weather)
let result = drawWithCodex({ id, prompt, outPath, images, log })
if (result !== 'ok') result = drawWithCodex({ id, prompt, outPath, images, log })
if (result !== 'ok') throw new Error(`${id}: 그림을 두 번 다 저장하지 못했어요`)
outfits.push({ persona, label: spec.personas[persona].label, style: outfit.style, labels, image: `/daily/${id}.webp`, source: pick.url, items: outfit.items })
}
writeFileSync(join(outDir, 'outfits.json'), JSON.stringify({ weather, outfits }, null, 1))
return { weather, outfits }
}
/** 카드(copy.outfits)에 넣는 꼴: 사람·제목·스타일·이름표·그림 주소 */
export const toCardOutfits = (outfits) => outfits.map(({ persona, label, style, labels, image }) => ({ persona, label, style, labels, image }))
if (process.argv[1]?.endsWith('daily-ootd.mjs')) {
const args = process.argv.slice(2)
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
const outArg = flag('--out')
const style = flag('--style') ?? 'minimal'
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const { outfits } = await runDailyOotd({ outDir: resolve(outArg ?? `out/${day}`), style })
const copy = Buffer.from(JSON.stringify({ outfits: JSON.stringify(toCardOutfits(outfits)), style, theme: 'sky' })).toString('base64url')
console.log(`카드 그리기: npm run card -- ootd --no-images --copy ${copy}`)
}