feat: 카드·영상 스크립트를 윈도우에서도 돌게 — 외부 프로그램 위치를 scripts/bin.mjs 로 모음, 크롬이 45초 넘게 멈추면 그 장만 다시 찍음, claude 프롬프트는 stdin 으로

This commit is contained in:
minaChoi committed 2026-10-29 09:05:31 +09:00
1 parent 63b4fa74fe
commit e28359ff47
15 files changed
+150 -51

No files matched your search

+11
View File
@@ -11,6 +11,17 @@ VITE_API_BASE_URL=http://localhost:9810 npm run dev # http://localhost:5175
백엔드 주소가 다르면 `VITE_API_BASE_URL`만 바꾼다. 백엔드 API가 바뀌면 `npm run api`로 `src/api/client`를 다시 만든다.
## 윈도우
스킬(`.claude/commands/` 의 daily-tarot·daily-ootd·daily-cards·weekly-ootd-video)은 Git Bash 에서 맥과 같은 명령으로 돈다. 외부 프로그램 위치는 `scripts/bin.mjs` 가 운영체제별로 찾는다. 처음 한 번:
1. 설치: `winget install Git.Git OpenJS.NodeJS.LTS Python.Python.3.12 Gyan.FFmpeg Google.Chrome` (ffmpeg 가 JPEG·webp 변환도 한다). Claude Code 는 네이티브 설치(`claude.exe`), Codex 는 `npm i -g @openai/codex` 후 `codex login`.
2. Claude Code 설정(`%USERPROFILE%\.claude\settings.json`)의 `env` 에 `"PYTHON": "python"`, `"PYTHONUTF8": "1"` (스킬의 `${PYTHON:-python3}` 와 파이썬 한글 출력).
3. 크롬이 기본 위치(Program Files·LocalAppData)에 없으면 `CHROME_PATH`, claude·codex 를 못 찾는다고 나오면 `CLAUDE_BIN`·`CODEX_BIN` 에 실행 파일 경로.
4. `%USERPROFILE%\.ssh\config` 에 맥 `~/.ssh/config` 와 같은 `King_admin`(ProxyJump Confluence)과 키. `ssh -o BatchMode=yes King_admin true` 가 비밀번호 없이 돼야 한다.
5. 저장소를 받고 `admin` 에서 `npm install`. 개인 스킬로 쓰려면 `.claude/commands/<이름>.md` 를 `%USERPROFILE%\.claude\skills\<이름>\SKILL.md` 로 복사한다.
6. 영상(weekly-ootd-video)은 `~/.config/nalssigak/`(YouTube OAuth 파일)도 옮긴다.
## 카드 만드는 흐름
1. **템플릿 고르기**: `tarot`(날씨 타로, 5장) · `ootd`(오늘의 코디, 6장). 코디는 주제·Claude 기획 대신 스타일(캐주얼·세미정장·정장·스트릿·꾸안꾸, copy의 `style`)을 고른다. 지역은 고르지 않는다. 모든 카드는 서울(중구) 오늘 예보로 만들고, 카드에 지역 이름은 넣지 않는다.
+1 -1
View File
@@ -16,7 +16,7 @@ done
for name in woman_a woman_b man_a man_b; do
[ -s "$name.mp4" ] && { echo "$name 이미 있음"; continue; }
echo "== $name 시작 $(date +%H:%M:%S)"
python3 "$HERE/generate.py" --image "${name%_*}_first.png" --prompt-file "$name.txt" --negative "$negative" \
"${PYTHON:-python3}" "$HERE/generate.py" --image "${name%_*}_first.png" --prompt-file "$name.txt" --negative "$negative" \
--duration 4 --seed $((RANDOM % 9000 + 100)) --anchor-end --keep-running --output "$name.mp4"
echo "== $name 완료 $(date +%H:%M:%S)"
done
+2 -2
View File
@@ -30,12 +30,12 @@ def main():
"",
Path(args.prompt_file).read_text(encoding="utf-8").strip(),
])
command = ["codex", "exec", "--skip-git-repo-check", "-C", str(work), "-s", "workspace-write", "-m", IMAGE_MODEL,
command = [os.environ.get("CODEX_BIN") or shutil.which("codex") or "codex", "exec", "--skip-git-repo-check", "-C", str(work), "-s", "workspace-write", "-m", IMAGE_MODEL,
"-c", 'model_reasoning_effort="low"']
for image in args.image:
command += ["-i", str(Path(image).resolve())]
try:
subprocess.run(command, input=task, text=True, stdout=subprocess.DEVNULL, check=True)
subprocess.run(command, input=task, encoding="utf-8", stdout=subprocess.DEVNULL, check=True)
result = work / "result.png"
if not result.is_file():
pngs = sorted(work.glob("*.png"))
+8 -6
View File
@@ -7,12 +7,14 @@ set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(cd "$1" && pwd)
MUSIC=${2:-}
# 윈도우는 python3 대신 python·py 일 수 있다
PY=${PYTHON:-python3}
cd "$WORK"
[ -s mask.png ] || python3 "$HERE/render.py" mask --out mask.png
[ -s frame.png ] || python3 "$HERE/render.py" frame --out frame.png
[ -s outro.png ] || python3 "$HERE/render.py" outro --out outro.png
[ -s mask.png ] || "$PY" "$HERE/render.py" mask --out mask.png
[ -s frame.png ] || "$PY" "$HERE/render.py" frame --out frame.png
[ -s outro.png ] || "$PY" "$HERE/render.py" outro --out outro.png
part=6.7; outro=2.4; fade=0.4
o1=$(python3 -c "print($part - $fade)"); o2=$(python3 -c "print(2 * $part - 2 * $fade)")
o1=$(awk "BEGIN{print $part - $fade}"); o2=$(awk "BEGIN{print 2 * $part - 2 * $fade}")
card="scale=816:1440:flags=lanczos,format=rgba"
blur="scale=272:480,boxblur=10:2,scale=1088:1920,crop=1080:1920:4:0,eq=brightness=0.03:saturation=0.9,format=rgba"
join() { # 클립a 클립b 이름
@@ -37,11 +39,11 @@ inputs=(); chain=""; prev="0:v"; k=1
while read -r name start end; do
[ -n "${name:-}" ] || continue
inputs+=(-loop 1 -framerate 24 -t 15 -i "bubbles/$name.png")
fo=$(python3 -c "print(round($end - 0.2, 2))")
fo=$(awk "BEGIN{printf \"%g\", $end - 0.2}")
chain+="[$k:v]format=rgba,fade=in:st=$start:d=0.2:alpha=1,fade=out:st=$fo:d=0.2:alpha=1[b$k];"
chain+="[$prev][b$k]overlay=x=0:y='max(0\,20*(1-(t-$start)/0.2))':enable='between(t,$start,$end)'[v$k];"
prev="v$k"; k=$((k+1))
done < bubbles.txt
done < <(tr -d '\r' < bubbles.txt)
if [ $k -eq 1 ]; then cp base.mp4 bubbles.mp4; else
ffmpeg -hide_banner -loglevel error -y -i base.mp4 "${inputs[@]}" -filter_complex "${chain%;}" -map "[$prev]" -map 0:a \
-c:v libx264 -preset slow -crf 17 -profile:v high -pix_fmt yuv420p -c:a copy -movflags +faststart bubbles.mp4
+1 -1
View File
@@ -156,7 +156,7 @@ def main():
if side % 64 or not 256 <= side <= 2048:
sys.exit("width와 height는 256~2048 사이 64의 배수여야 합니다")
server = [str(HERE / "server.sh")]
server = ["bash", str(HERE / "server.sh")]
if subprocess.run(server + ["up"]).returncode != 0:
sys.exit("전용 컨테이너를 시작하지 못했습니다")
with socket.socket() as sock:
+14 -1
View File
@@ -18,7 +18,20 @@ import urllib.parse
from pathlib import Path
TEMPLATES = Path(__file__).resolve().parent.parent / "templates"
CHROME = os.environ.get("CHROME_BIN", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
def _chrome():
env = os.environ.get("CHROME_BIN") or os.environ.get("CHROME_PATH")
if env:
return env
if sys.platform == "win32":
for base in (os.environ.get("PROGRAMFILES"), os.environ.get("PROGRAMFILES(X86)"), os.environ.get("LOCALAPPDATA")):
path = Path(base or "") / "Google/Chrome/Application/chrome.exe"
if base and path.is_file():
return str(path)
return "chrome.exe"
return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" if sys.platform == "darwin" else "google-chrome"
CHROME = _chrome()
# compose.sh 의 영상 창 크기와 같아야 한다
CARD = (816, 1440)
+51
View File
@@ -0,0 +1,51 @@
// 외부 프로그램(크롬·claude·codex·ffmpeg) 위치와 부르는 법. 맥·윈도우 둘 다에서 돌게 한 곳에 모은다.
import { execFileSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
const WIN = process.platform === 'win32'
export const CHROME =
process.env.CHROME_PATH ??
(WIN
? [`${process.env.PROGRAMFILES}/Google/Chrome/Application/chrome.exe`, `${process.env['PROGRAMFILES(X86)']}/Google/Chrome/Application/chrome.exe`, `${process.env.LOCALAPPDATA}/Google/Chrome/Application/chrome.exe`].find((p) => existsSync(p)) ?? 'chrome.exe'
: process.platform === 'darwin'
? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
: 'google-chrome')
/**
* execFile 로 부를 [실행 파일, ...앞 인자]. CLAUDE_BIN·CODEX_BIN 환경변수로 바꿀 수 있다.
* 윈도우에서 npm 으로 깐 CLI 는 .cmd 라 shell 없이는 못 부르므로(인자 따옴표가 깨짐) .cmd 가 가리키는 .js 를 node 로 직접 부른다.
*/
export function cli(name) {
const override = process.env[`${name.toUpperCase()}_BIN`]
if (override) return [override]
if (!WIN) return [name]
let hits = []
try {
hits = execFileSync('where', [name], { encoding: 'utf8' }).split(/\r?\n/).filter(Boolean)
} catch {
throw new Error(`${name} 을(를) 찾지 못했어요. 설치했는지 보고, ${name.toUpperCase()}_BIN 환경변수로 실행 파일 경로를 알려 주세요.`)
}
const exe = hits.find((p) => p.toLowerCase().endsWith('.exe'))
if (exe) return [exe]
const shim = hits.find((p) => p.toLowerCase().endsWith('.cmd'))
const js = shim && readFileSync(shim, 'utf8').match(/%dp0%\\([^"]+?\.js)/)?.[1]
if (!js) throw new Error(`${name} 실행 파일(${hits.join(', ')})을 부를 수 없어요. ${name.toUpperCase()}_BIN 환경변수로 .exe 경로를 알려 주세요.`)
return [process.execPath, join(dirname(shim), js)]
}
/** png → jpg (품질 높게) */
export function toJpeg(png, jpg) {
execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', png, '-q:v', '2', jpg], { stdio: 'ignore' })
}
/** png → webp, 가로 width 로 줄인다. cwebp 가 있으면 쓰고(맥 brew), 없으면 ffmpeg 의 libwebp(윈도우 배포판에 들어 있다) */
export function toWebp(png, webp, width = 1024) {
try {
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', String(width), '0', png, '-o', webp])
} catch (e) {
if (e.code !== 'ENOENT') throw e
execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', png, '-vf', `scale=${width}:-1`, '-c:v', 'libwebp', '-quality', '88', webp])
}
}
+12 -5
View File
@@ -8,6 +8,7 @@
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)
@@ -16,7 +17,6 @@ const AUTO_PLAN = ['tarot']
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'
const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
function fail(message) {
console.error(message)
@@ -46,7 +46,7 @@ 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 (!existsSync(CHROME)) fail(`Chrome을 찾지 못했어요: ${CHROME}\nCHROME_PATH 환경변수로 경로를 알려 주세요.`)
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 를 먼저 켜 주세요.`))
@@ -128,7 +128,7 @@ for (let slide = 1; slide <= SLIDES[template]; slide++) {
if (copy) query.set('copy', copy)
const png = resolve(outDir, `${day}_${template}_${slide}.png`)
const jpg = png.replace(/\.png$/, '.jpg')
execFileSync(CHROME, [
const shot = [
'--headless=new',
'--disable-gpu',
'--hide-scrollbars',
@@ -137,8 +137,15 @@ for (let slide = 1; slide <= SLIDES[template]; slide++) {
'--virtual-time-budget=20000',
`--screenshot=${png}`,
`${ADMIN_URL}/render?${query}`,
], { stdio: 'ignore' })
execFileSync('sips', ['-s', 'format', 'jpeg', '-s', 'formatOptions', '92', png, '--out', jpg], { stdio: 'ignore' })
]
// 크롬이 한 장에서 멈추는 일이 있어 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)
}
+4 -2
View File
@@ -3,6 +3,7 @@ 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'
@@ -27,7 +28,8 @@ export function drawWithCodex({ id, prompt, outPath, images = [], log = console.
try {
// -i 는 파일을 여러 개 받아서 뒤의 프롬프트까지 파일로 읽는다 → 프롬프트는 stdin 으로 준다
const imageArgs = images.flatMap((p) => ['-i', p])
execFileSync('codex', ['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'] })
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}). 사용 한도나 로그인을 확인하세요.`)
@@ -37,7 +39,7 @@ export function drawWithCodex({ id, prompt, outPath, images = [], log = console.
log(`${id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
return 'not-saved'
}
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath])
toWebp(join(work, png), outPath)
rmSync(work, { recursive: true, force: true })
log(`${id}: ${outPath}`)
return 'ok'
+7 -2
View File
@@ -1,6 +1,7 @@
// 고른 스냅(사진 + 입은 상품 목록)에서 카드에 쓸 옷 목록을 Claude CLI로 뽑는다: 자리별 한글 이름표와 그림용 영어 설명.
import { execFile } from 'node:child_process'
import { tmpdir } from 'node:os'
import { cli } from './bin.mjs'
const SLOT_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
const PERSONA_TEXT = { f20: '20-30대 여자', m20: '20-30대 남자', f40: '40대 이상 여자', m40: '40대 이상 남자' }
@@ -55,9 +56,12 @@ function buildPrompt(pick, persona, weather) {
/** @returns {Promise<{ style: string, items: { slot: string, label: string, prompt: string }[] }>} */
export function extractOutfit(pick, persona, weather) {
const args = ['-p', buildPrompt(pick, persona, weather), '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--tools', 'Read', '--allowedTools', 'Read', '--no-session-persistence', '--model', 'sonnet']
// 프롬프트는 길고 여러 줄이라 명령줄(윈도우는 길이 제한) 대신 stdin 으로 준다
const prompt = buildPrompt(pick, persona, weather)
return new Promise((done, fail) => {
execFile('claude', args, { cwd: tmpdir(), timeout: 240_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
const [claude, ...pre] = cli('claude')
const args = [...pre, '-p', '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--tools', 'Read', '--allowedTools', 'Read', '--no-session-persistence', '--model', 'sonnet']
const child = execFile(claude, args, { cwd: tmpdir(), timeout: 240_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
let out
try {
@@ -72,5 +76,6 @@ export function extractOutfit(pick, persona, weather) {
items.sort((a, b) => SLOT_ORDER.indexOf(a.slot) - SLOT_ORDER.indexOf(b.slot))
done({ style: String(result.style ?? '').trim() || '데일리', items })
})
child.stdin.end(prompt)
})
}
+7 -2
View File
@@ -4,6 +4,7 @@ import { execFile } from 'node:child_process'
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { resolve } from 'node:path'
import { cli } from './bin.mjs'
const pngNames = (dir) =>
readdirSync(resolve(import.meta.dirname, dir))
@@ -146,9 +147,12 @@ function schema(ctx, fixed = {}, topic = '') {
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed, topic)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
// 프롬프트는 길고 여러 줄이라 명령줄(윈도우는 길이 제한) 대신 stdin 으로 준다
const prompt = buildPrompt(ctx, { topic, feedback, fixed })
return new Promise((done, fail) => {
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
const [claude, ...pre] = cli('claude')
const args = [...pre, '-p', '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed, topic)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
const child = execFile(claude, args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
let out
try {
@@ -178,5 +182,6 @@ export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
if (isTarot(ctx)) for (const k of ['c1', 'c2', 'c3', 'i1', 'i2', 'i3']) if (result[k]) copy[k] = result[k]
done({ topic: finalTopic, copy })
})
child.stdin.end(prompt)
})
}