Files
o2o-weather/admin/scripts/daily-ootd.mjs
T

95 lines
5.7 KiB
JavaScript

// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
import { 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 morningC = Math.round((t.find((s) => hour(s) === 6) ?? t[0]).temp_c)
const band = spec.bands.find((b) => maxC >= 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.`
}
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, log = console.log }) {
const weather = await weatherToday()
log(`오늘 ${weather.day}: 아침 ${weather.morningC}° · 낮 ${weather.maxC}° → 구간 ${weather.band}`)
mkdirSync(outDir, { recursive: true })
const picks = await pickSnaps({ band: weather.band, 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)
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 outArg = args.includes('--out') ? args[args.indexOf('--out') + 1] : null
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const { outfits } = await runDailyOotd({ outDir: resolve(outArg ?? `out/${day}`) })
const copy = Buffer.from(JSON.stringify({ outfits: JSON.stringify(toCardOutfits(outfits)), theme: 'sky' })).toString('base64url')
console.log(`카드 그리기: npm run card -- ootd --no-images --copy ${copy}`)
}