feat: 이번주 코디 영상 스크립트·템플릿·모델 사진과 명령 파일 추가, 클립 동작은 후보에서 무작위로 고름 (손가락 모양 동작 제외), .sh·.py·.mjs 는 LF 로 받음

This commit is contained in:
minaChoi committed 2026-10-29 08:52:40 +09:00
1 parent 1ec87a82c1
commit 56f71cdfbe
54 files changed
+1576

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
---
description: 이번주 코디 숏폼 영상(여자 → 남자 → 날씨각 마무리, 15초)을 날씨각 가상 모델과 무신사 스냅으로 만들어 검토받고 인스타 릴스·YouTube Shorts에 올린다
argument-hint: "<나이대> 20·30·40 [스타일] minimal·casual·semi·formal·street (비우면 casual)"
---
이번주 코디 영상을 만들어 올린다. 인자: `$ARGUMENTS` — 첫 번째는 나이대(`20`·`30`·`40`, 필수), 두 번째는 코디 스타일(minimal=꾸안꾸, casual, semi=오피스, formal, street, 비우면 casual).
나이대별로 쓰는 것: `20`·`30` → 20대 모델(models.json age 20s)·무신사 20-30대 스냅(`f20`·`m20`)·타이틀 "20대"/"30대", `40` → 40대 모델(40s)·무신사 40대~ 스냅(`f40`·`m40`)·타이틀 "40대~"(`--age 40~`).
작업 폴더 `W` = `admin/nalssigak/runs/<오늘 날짜>-<나이대>/` (커밋하지 않는다). 스크립트는 `admin/nalssigak/scripts/`, 템플릿은 `admin/nalssigak/templates/`.
승인 지점(5·10번)에서는 반드시 멈추고 사용자 답을 기다린다. 업로드는 사용자가 "올려"라고 한 뒤에만 한다(올린 건 되돌릴 수 없다).
## 꼭 지킬 것
- 얼굴은 `admin/nalssigak/models/` 의 가상 모델만 쓴다. 연예인·유명인·남의 사진, 그 사람을 닮게 만든 이미지는 사용자가 친구·본인 사진이라고 해도 기준 이미지로 쓰지 않는다. 새 모델이 필요하면 `models/prompts/` 처럼 글로만 만들고("ORIGINAL FICTIONAL … must not resemble any real celebrity"), 시안을 보여 주고 고르게 한다.
- 올리는 문구(YouTube 제목·설명·태그, 인스타 캡션·해시태그, 말풍선)에 무신사 상품명·브랜드명·'무신사'·스냅 주소를 쓰지 않는다. 옷은 일반 이름(색·소재·종류)으로만 말한다. 예: `우먼즈 신세틱 스웨이드 블루종 재킷 [다크 브라운]` → `다크 브라운 스웨이드 블루종`, `BELLA QUILTED MARYJANES` → `블랙 메리제인 플랫`.
- 옷은 무신사 인기 스냅에 태그된 상품만 쓴다(`admin/scripts/snap.mjs`). 에이블리는 공개 API 가 없어 쓸 수 없다. 요청에 있어도 처음에 말하고 무신사로 만든다.
- 계절감: 아침 체감과 낮 최고 평균이 12도 미만(구간 chilly 이하)이면 두 사람 다 겉옷이 있어야 하고, 반팔 단독·미니·뮬·샌들은 안 된다(미니는 검은 스타킹과 롱부츠를 함께 신으면 된다). 여자 코디는 카고·백팩·등산화·바람막이 같은 고프코어를 피한다.
- 움직임: 춤추지 않는다. 원래 자세에서 바람에 머리·옷이 날리고 손인사·머리 넘기기·옷깃 만지기 같은 작은 동작 하나만(`templates/actions.json`). 손가락 모양 동작(하트·V·OK·엄지)은 영상에서 다른 손 모양이 되니 쓰지 않는다. 낙엽 떨어지는 효과는 넣지 않는다. 여자는 키가 커 보이지 않게(158cm 정도, 머리:몸 1:7, 눈높이 카메라).
- 화면: 프로필 그리드는 가운데 3:4(위 240 ~ 아래 1680), 피드는 4:5(위 285 ~ 아래 1635)만 보여 준다. 둥근 영상 창(132,240 · 816×1440)이 3:4 를 채우고 바깥은 같은 영상을 흐리게 깔아 빈 곳이 없게 한다. 칩·제목·자막은 창 왼쪽 아래, 4:5 안에 둔다. `templates/frame.html`·`title.html`·`bubble.html`·`scripts/compose.sh` 의 창 위치를 바꾸지 않는다.
- 킹서버: 영상은 날씨각 전용 컨테이너 `nalssigak-ltx`(GPU 0)로만 만든다. menusong 서비스·파일은 건드리지 않는다. `server.sh down` 이 끌 때 서버의 입력·결과 파일을 지운다.
- 비밀: OAuth·토큰은 `~/.config/nalssigak/`, 인스타 토큰은 `.env`. 값을 출력하거나 저장소에 넣지 않는다.
## 환경 점검 (1번에서 돌리고, 안 되면 해결 방법을 알려 준다)
| 점검 | 명령 | 안 될 때 |
|---|---|---|
| 기본 도구 | `python3 --version; node --version; ffmpeg -version; ls "/Applications/Google Chrome.app"` | 없는 것을 설치한다(`brew install ffmpeg` 등). 크롬은 앱으로 설치. |
| Codex(사진) | `codex --version` | Codex CLI 를 설치하고 `codex login`. 사용 한도 초과면 다음 날 다시. |
| 관리자 서버(인스타) | `curl -s http://localhost:5175/api/targets` 에 `king` | `admin/` 에서 `npm install` 후 `admin/AGENTS.md` '켜기'대로 백그라운드로 켠다(킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다). |
| 킹서버 접속 | `ssh -o BatchMode=yes King_admin true` | `~/.ssh/config` 에 `Host King_admin`(HostName 172.30.1.36, User o2oadmin, ProxyJump Confluence)과 키가 있어야 한다. 사내망·키는 사용자가 확인. |
| 영상 서버 | `admin/nalssigak/scripts/server.sh status` | 이미지 `jw/comfyui-ltx:latest`·모델 `/mnt/data2/dir/jw_playground/LTX-2.5` 가 서버에 있어야 한다(없으면 서버 담당자에게). GPU 0 을 menusong 이 쓰면 기다리거나 `OOTD_GPU=1`. |
| YouTube 앱 | `ls ~/.config/nalssigak/client_secret.json` | Google Cloud 의 YouTube Data API v3 프로젝트에서 OAuth 클라이언트(데스크톱 앱) JSON 을 받아 그 경로에 두고 `chmod 600`. |
| YouTube 로그인 | `ls ~/.config/nalssigak/youtube_token.json` | `python3 admin/nalssigak/scripts/youtube.py auth` → 사용자가 채널 계정으로 로그인. 'access_denied' 면 Google 인증 플랫폼 → 대상 → 테스트 사용자에 그 계정을 추가. 업로드 때 `invalid_grant` 면 토큰 만료(테스트 앱은 7일)라 auth 를 다시 하고, 앱을 '프로덕션으로 게시'하길 권한다. |
| 인스타 토큰 | 킹서버 `.env` 의 `INSTAGRAM_ACCESS_TOKEN`·`INSTAGRAM_USER_ID` 가 있는지(값은 보지 않고 `grep -c`) | 없거나 만료면 `TODO.md` '인스타 연결' 행 순서대로 다시 발급해 킹서버 `.env` 에 넣는다(사용자 작업). |
## 순서
1. 준비 확인: 아래 '환경 점검' 명령을 모두 돌린다. 안 되는 항목이 있으면 그 항목의 해결 방법을 사용자에게 그대로 알려 주고, 사용자가 할 일(로그인·키 발급 등)이 아니면 직접 고친 뒤 다시 점검한다. 다 통과해야 2번으로 간다.
2. 날씨: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `slots` 중 6~21시로 아침(6시)·낮 최고 기온, 비(rain_type≠0 또는 rain_prob≥60), 하늘을 잡는다. 구간은 낮 최고로 hot≥28 · warm≥23 · mild≥17 · cool≥12 · chilly≥9 · cold≥5 · 그 아래 freezing. 배경 문장은 계절·날씨에 맞게 한 줄로(예: 맑은 가을이면 "a sunny clear late-October afternoon on a Seoul tree-lined sidewalk with golden ginkgo trees…", 비 오면 젖은 거리·우산).
3. 코디: `cd admin && node scripts/snap.mjs --band <구간> --style <스타일> --out nalssigak/runs/<W 이름>/snaps`. 20·30 은 `f20`·`m20`, 40 은 `f40`·`m40` 을 쓴다. `snaps/picks.json` 의 상품(outer·top·bottom·shoes·bag)을 보고 위 계절감 규칙에 맞는지 본다. 안 맞으면 `--pages 3` 등으로 다시 고른다.
4. 사진: `models/models.json` 에서 그 나이대(20·30 → 20s, 40 → 40s) 여자·남자를 하나씩 무작위로 고른다. `templates/photo_prompt.txt` 를 채워 `W/woman_photo.txt`·`W/man_photo.txt` 를 쓰고(옷은 태그된 상품을 색·소재·실루엣까지 영어로, 여자는 body_line 에 키 규칙), 둘을 동시에 만든다:
`python3 admin/nalssigak/scripts/codex_image.py --prompt-file W/woman_photo.txt --output W/woman_photo.png --image admin/nalssigak/models/<id>.jpg --image W/snaps/f20/snap.jpg --image W/snaps/f20/goods-<n>.jpg …` (남자도 같게, 1~2분).
5. 사진 검수 → **승인 대기**: 모델 기준 사진과 나란히 붙인 시트를 열어 보여 준다. 볼 것: 같은 얼굴인지, 태그된 옷이 다 있고 없는 옷이 없는지, 글자·워터마크, 전신(머리~신발, 신발 아래 여백), 손, 키 비율. 사용자가 고치라고 하면 그 사진만 다시 만든다.
6. 동작 설명: 동작은 사람마다 무작위로 두 개를 고른다 — `python3 admin/nalssigak/scripts/actions.py --who woman --has outer,bag` (그 사람에게 겉옷·가방이 있을 때만 `--has` 에 넣는다, 남자는 `--who man`). 출력 첫 줄을 `W/woman_a.txt`, 둘째 줄을 `W/woman_b.txt` 의 `{action}` 에 그대로 넣어 `templates/motion_prompt.txt` 를 채운다(남자는 `W/man_a.txt`·`W/man_b.txt`). 손가락 모양 동작을 따로 덧붙이지 않는다.
7. 클립: `admin/nalssigak/scripts/clips.sh W` (4초 4개, 하나에 4~5분, 총 20분 안팎). GPU 0 을 menusong 이 쓰고 있다며 시작하지 않으면 기다렸다 다시 하거나 비어 있으면 `OOTD_GPU=1` 로 한다.
8. 클립 검수: 클립마다 `ffmpeg -vf "select='eq(n\,12)+eq(n\,36)+eq(n\,60)+eq(n\,84)',tile=4x1"` 로 얼굴을 확대해 본다. 눈 감음·고개 젖힘·얼굴 바뀜·손가락 뭉개짐·카메라 움직임이 있으면 그 클립만 `clips.sh W woman_b` 처럼 다시 만든다(최대 2번).
9. 합성:
- 타이틀: `python3 admin/nalssigak/scripts/render.py title --age <20|30|40~> --who 여성 --label <코디|하객룩 …> --out W/title_woman.png` (남성도). 제목은 '이번주 20대 / 여성 하객룩' 두 줄로 창 왼쪽 아래에 얹힌다.
- 자막 4개: 그날 옷에서 한 줄로 짧게(20자 안팎, 옷 이름은 `*강조*`). 문구는 목록으로 먼저 확인받는다. 제목 아래 같은 자리(창 왼쪽, 발 바로 위 다리 높이)에 차례로 나오고, 창 오른쪽(948px)을 넘으면 문구를 줄인다. 자막·제목이 신발을 가리면 안 된다.
`python3 admin/nalssigak/scripts/render.py bubble --text "…" --out W/bubbles/w1.png`, `W/bubbles.txt` 에 `w1 0.8 3.0` · `w2 3.4 6.1` · `m1 7.1 9.4` · `m2 9.8 12.4`.
- 음악: `admin/nalssigak/music.json` 에서 직전 회차(`runs/*/publish.md` 의 Music 줄)와 다른 곡을 골라 `admin/nalssigak/runs/cache/music/<id>.mp3` 에 없으면 내려받는다. 새 곡은 Mixkit Stock Music Free License 곡을 후보로 영상에 입혀 들려 주고 사용자가 고른 것만 넣는다.
- `admin/nalssigak/scripts/compose.sh W admin/nalssigak/runs/cache/music/<id>.mp3` → `W/final.mp4` (15초).
- 확인: `admin/nalssigak/scripts/sheet.sh W/final.mp4 W/sheet.png 1.0 1.9 2.8 3.7 4.7 5.8 7.4 8.3 9.2 10.1 11.1 12.2 13.8` 로 자막·제목이 얼굴을 가리지 않는지 보고, `crop=1080:1440:0:240`(그리드)·`crop=1080:1350:0:285`(피드)로 잘라 칩·제목·자막·머리·신발이 다 보이는지 본다.
10. 문구 → **승인 대기**: `W/publish.md` 에 YouTube 제목(`이번주 <나이>대 <계절> 코디 🍂 여자·남자 데일리룩 | 날씨각 #Shorts` 꼴, 나이는 타이틀과 같게 `20대`·`30대`·`40대~` — 40 은 반드시 `40대~`. 제목·설명·인스타 캡션 첫 줄 모두 같다)·설명(사람별 옷 목록 — 옷 이름은 '다크 브라운 스웨이드 블루종'·'와이드 치노 팬츠'처럼 색·소재·종류로만 쓴다, weather.o2o.kr, "※ 영상 속 인물은 AI로 만든 가상 모델이에요." 와 음악 credit, 해시태그)·태그, 인스타 캡션(첫 줄이 제목, 프로필 링크 → weather.o2o.kr, 토스 '날씨각' 검색 안내, AI 표기, 해시태그)을 쓴다. 해시태그는 나이대·스타일·계절에 맞춘다. 영상을 열고 문구 전체를 보여 준 뒤 "올려" 를 기다린다.
11. 올리기(승인 후):
- 인스타: 1초 프레임을 `W/cover.jpg` 로 뽑고, `POST http://localhost:5175/api/reel?target=king` 에 `{title, caption, hashtags, video(mp4 base64, 30MB 이하), cover(JPEG base64)}` → `reel_id`, 이어서 `POST http://localhost:5175/api/reel/<reel_id>/instagram?target=king` (`--max-time 600`) → `ig_media_id`. 링크는 `GET https://graph.instagram.com/v24.0/<ig_media_id>?fields=permalink,media_product_type` (토큰은 `~/projects/o2o-weather/.env` 또는 킹서버 `~/proj/o2o-weather/.env` 의 `INSTAGRAM_ACCESS_TOKEN`, 출력하지 않는다). `Application request limit reached` 면 `me/media?fields=permalink,caption,timestamp&limit=1` 로 이미 올라갔는지 보고, 없을 때만 다시 올린다.
- YouTube: `W/youtube_meta.json` 에 `{title, description, tags, privacy}` 를 쓰고 `python3 admin/nalssigak/scripts/youtube.py upload W/final.mp4 W/youtube_meta.json`. 토큰이 없거나 만료면 `youtube.py auth` 로 사용자에게 채널 계정 로그인을 받는다(계정이 Google 인증 플랫폼 테스트 사용자여야 한다).
- privacy: `~/.config/nalssigak/youtube_public` 파일이 있으면 `"public"`(API 감사 통과 뒤), 없으면 `"private"`. 감사 전에는 절대 public 으로 보내지 않는다(비공개로 잠길 수 있다).
- 바로 반영: 비공개로 올렸으면 출력의 `studio` 주소를 `open` 으로 열고, 사용자에게 "공개 범위 → 공개 → 저장" 만 하면 된다고 알린다. 사용자가 공개로 바꿨다고 하면 `https://youtube.com/shorts/<id>` 링크를 다시 알려 주고 마친다.
- public 으로 보냈는데 출력에 경고(요청과 다른 공개 상태)가 나오면 감사가 풀린 게 아니므로 `youtube_public` 파일을 지우라고 알리고, 스튜디오에서 상태를 확인하게 한다.
- 감사 신청은 YouTube API Services 감사·할당량 양식(https://support.google.com/youtube/contact/yt_api_form)으로 사용자가 한다.
12. 보고(한국어, 짧게): 인스타·YouTube 링크, 쓴 모델·스냅 주소, 검수에서 다시 만든 것, 남은 일(YouTube 는 비공개로 올라가니 스튜디오에서 공개 전환, 인스타는 앱에서 'AI 정보' 라벨 켜기).
+4
View File
@@ -0,0 +1,4 @@
# 셸·파이썬 스크립트는 윈도우에서 받아도 LF 로 둔다 (CRLF 면 Git Bash 가 $'\r' 오류를 낸다)
*.sh text eol=lf
*.py text eol=lf
*.mjs text eol=lf
+3
View File
@@ -28,3 +28,6 @@ out
# 그날 코디 그림 (scripts/daily-ootd.mjs 가 만들고 카드가 /daily/... 로 읽는다)
public/daily
# 날씨각 코디 영상 작업 폴더 (nalssigak/scripts 가 만든다)
nalssigak/runs
Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 KiB

+82
View File
@@ -0,0 +1,82 @@
{
"about": "날씨각 가상 모델(실존 인물을 닮지 않게 만든 얼굴). 20s 는 20-30대 코디(나이대 20·30), 40s 는 40대~ 코디(나이대 40)에 쓴다. 사진 프롬프트의 첫 참고 이미지로 쓰고, look 은 동작 설명에 넣는다. 만든 프롬프트는 prompts/",
"women": [
{
"id": "f1",
"age": "20s",
"look": "long straight black hair, a soft innocent face with a gentle closed-lip smile"
},
{
"id": "f2",
"age": "20s",
"look": "long wavy light brown hair, a bright cheerful face with a lively smile"
},
{
"id": "f3",
"age": "20s",
"look": "a chic chin-length black bob with blunt bangs, a cool calm expression"
},
{
"id": "f4",
"age": "20s",
"look": "long dark brown hair with see-through bangs, an elegant face with a soft smile"
},
{
"id": "f41",
"age": "40s",
"look": "long soft wavy brown hair, an elegant refined face with a gentle closed-lip smile"
},
{
"id": "f42",
"age": "40s",
"look": "a shoulder-length straight dark brown bob with a center part, a calm natural face"
},
{
"id": "f43",
"age": "40s",
"look": "medium-length tousled wavy black hair, a chic confident face with a warm smile"
}
],
"men": [
{
"id": "m2",
"age": "20s",
"look": "soft brown hair with fluffy bangs, a friendly face with a warm smile"
},
{
"id": "m3",
"age": "20s",
"look": "a short neat black two-block haircut, a clean composed face"
},
{
"id": "m5",
"age": "20s",
"look": "golden blond hair with soft bangs, a bright cheerful smile"
},
{
"id": "m6",
"age": "20s",
"look": "jaw-length layered jet black hair parted in the middle, calm sharp eyes"
},
{
"id": "m7",
"age": "20s",
"look": "short textured spiky jet black hair with piecey bangs, sharp eyes, a cool composed face"
},
{
"id": "m41",
"age": "40s",
"look": "short neat black hair with a slight side sweep, a gentle calm face with a soft smile"
},
{
"id": "m42",
"age": "40s",
"look": "well-groomed short side-parted black hair, thin black-rimmed glasses, a confident warm smile"
},
{
"id": "m43",
"age": "40s",
"look": "short slicked-back black hair, a sharp confident face with a composed expression"
}
]
}
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: long straight black hair past the shoulders, soft innocent face with a gentle closed-lip smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: long wavy light brown hair, bright cheerful face with a lively smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: chic chin-length black bob with blunt bangs, cool calm expression.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: long dark brown hair with see-through bangs, elegant graceful face with a soft smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: long soft wavy brown hair past the shoulders, an elegant refined face with a gentle closed-lip smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: shoulder-length straight dark brown bob with a center part, a calm natural face with a soft expression.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Woman: medium-length tousled wavy black hair, a chic confident face with a warm smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: soft brown hair with fluffy bangs, friendly puppy-like face with a warm smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: short neat black two-block haircut, clean dandy look, composed expression.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: short neat black hair with a slight side sweep, a gentle calm face with a soft smile.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: handsome and stylish, well-groomed short side-parted black hair, thin modern black-rimmed glasses, a defined jawline, clear skin, fit slim build, a confident warm smile, a refined smart office look.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early-to-mid 40s who must not resemble any real celebrity, actor, idol or public figure. Natural mature skin with subtle fine lines, healthy and well-groomed. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: short slicked-back black hair, a sharp confident face with a composed expression.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: golden blond hair with soft bangs, bright big cheerful smile showing a little teeth, friendly eyes.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man: jaw-length layered jet black hair parted in the middle, sharp calm eyes, composed cool expression, slim tall build.
+1
View File
@@ -0,0 +1 @@
Photorealistic full-body fashion lookbook photo, vertical 2:3 portrait, of an ORIGINAL FICTIONAL Korean person in their early 20s who must not resemble any real celebrity, idol or public figure. Standing straight facing the camera, whole body from head to shoes in frame with a little space above the head, arms relaxed, face clearly visible with natural skin texture, soft even studio light, plain light gray seamless studio background. Simple base outfit: plain white t-shirt, straight blue jeans and white sneakers. No text, no logo, no watermark. Man in his late 20s: short textured spiky jet black hair with piecey bangs, sharp narrow eyes, a defined jawline, a cool slightly serious expression.
+7
View File
@@ -0,0 +1,7 @@
{
"about": "배경음악은 상업 영상에 쓸 수 있고 출처 표기가 필요 없는 Mixkit Stock Music Free License 곡만 쓴다. 음원은 저장소에 넣지 않고 runs/cache/music 에 내려받는다. 사람이 들어 보고 고른 곡만 추가한다.",
"tracks": [
{"id": "mixkit-839", "title": "Tears of Joy", "artist": "Michael Ramir C.", "url": "https://assets.mixkit.co/music/839/839.mp3", "credit": "🎵 Music: Tears of Joy (Mixkit)"},
{"id": "mixkit-493", "title": "Beautiful Dream", "artist": "Diego Nava", "url": "https://assets.mixkit.co/music/493/493.mp3", "credit": "🎵 Music: Beautiful Dream (Mixkit)"}
]
}
+29
View File
@@ -0,0 +1,29 @@
"""클립 동작을 templates/actions.json 에서 무작위로 고른다. 한 사람의 a·b 클립이 같은 동작이 되지 않게 겹치지 않게 뽑는다.
python3 actions.py --who woman --has outer,bag # 두 줄 출력: a 클립 동작, b 클립 동작
"""
import argparse
import json
import random
from pathlib import Path
ACTIONS = Path(__file__).resolve().parent.parent / "templates" / "actions.json"
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--who", choices=["woman", "man"], required=True)
parser.add_argument("--has", default="", help="그 사람에게 있는 것 (outer, bag 을 쉼표로)")
parser.add_argument("--n", type=int, default=2)
args = parser.parse_args()
has = {h.strip() for h in args.has.split(",") if h.strip()}
pool = [a["text"] for a in json.loads(ACTIONS.read_text(encoding="utf-8"))[args.who] if set(a.get("needs", [])) <= has]
if len(pool) < args.n:
raise SystemExit(f"{args.who} 동작 후보가 {len(pool)}개라 {args.n}개를 고를 수 없어요")
print("\n".join(random.SystemRandom().sample(pool, args.n)))
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# usage: clips.sh <작업 폴더> [woman_a woman_b man_a man_b 중 다시 만들 것]
# 작업 폴더에 woman_photo.png·man_photo.png(코디 사진)와 woman_a.txt·woman_b.txt·man_a.txt·man_b.txt(동작 설명)를 두면
# 4초 클립 4개(woman_a.mp4 …)를 만든다. 이미 있는 클립은 건너뛰고, 이름을 주면 그 클립만 지우고 다시 만든다.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(cd "$1" && pwd); shift
cd "$WORK"
for name in "$@"; do rm -f "$name.mp4" "$name.workflow.json"; done
trap '"$HERE/server.sh" down' EXIT
negative=$(cat "$HERE/../templates/negative.txt")
for who in woman man; do
[ -s ${who}_first.png ] || ffmpeg -hide_banner -loglevel error -y -i ${who}_photo.png \
-vf "scale=1088:1920:force_original_aspect_ratio=increase:flags=lanczos,crop=1088:1920" -frames:v 1 ${who}_first.png
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" \
--duration 4 --seed $((RANDOM % 9000 + 100)) --anchor-end --keep-running --output "$name.mp4"
echo "== $name 완료 $(date +%H:%M:%S)"
done
+55
View File
@@ -0,0 +1,55 @@
"""Codex CLI의 내장 이미지 생성 도구로 그림 한 장을 만들어 PNG로 저장한다 (날씨각 sns/admin codex-image.mjs와 같은 방식).
usage: python3 codex_image.py --prompt-file p.txt --output out.png [--image ref.jpg ...]
"""
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
# 도구 호출·저장만 하므로 중간 모델·낮은 추론으로 고정한다 (sns/admin과 같은 이유)
IMAGE_MODEL = os.environ.get("CODEX_IMAGE_MODEL", "gpt-6-sol")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--prompt-file", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--image", action="append", default=[], help="참고 이미지 (여러 번 줄 수 있다)")
args = parser.parse_args()
work = Path(tempfile.mkdtemp(prefix="codex-image-"))
task = "\n".join([
"내장 이미지 생성 도구로 아래 프롬프트대로 이미지를 만든다."
+ (" 첨부한 참고 이미지는 프롬프트가 말한 용도로만 따른다." if args.image else ""),
"만든 이미지를 직접 열어 확인한다: 프롬프트와 다르거나 손·얼굴이 일그러졌거나 글자·로고가 있으면 한 번만 다시 만든다 (최대 2장).",
"통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.",
"",
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,
"-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)
result = work / "result.png"
if not result.is_file():
pngs = sorted(work.glob("*.png"))
if not pngs:
sys.exit(f"Codex가 그림을 저장하지 않았어요: {work}")
result = pngs[0]
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(result, args.output)
print("saved", args.output)
except subprocess.CalledProcessError as error:
sys.exit(f"Codex 실행이 실패했어요 ({error}). 사용 한도나 로그인을 확인하세요.")
finally:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
main()
+58
View File
@@ -0,0 +1,58 @@
#!/bin/bash
# usage: compose.sh <작업 폴더> [음악 mp3]
# 여자(woman_a+woman_b) 6.7초 → 남자(man_a+man_b) 6.7초 → 날씨각 마무리 2.4초, 0.4초 크로스페이드로 15초 final.mp4 를 만든다.
# 작업 폴더에 title_woman.png·title_man.png(render.py title)와 bubbles.txt("이름 시작초 끝초" 줄, PNG는 bubbles/이름.png)가 있어야 한다.
# 두 클립 이음새의 멈춘 구간은 빨리 감아 잇는다. 영상 창은 프로필 그리드 3:4(위 240 ~ 아래 1680)를 채우고 바깥은 같은 영상을 흐리게 깔며, 글자는 피드 4:5(위 285 ~ 아래 1635) 안에 둔다.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(cd "$1" && pwd)
MUSIC=${2:-}
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
part=6.7; outro=2.4; fade=0.4
o1=$(python3 -c "print($part - $fade)"); o2=$(python3 -c "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 이름
echo "[$1:v]split[$3a1][$3a2];[$3a1]trim=end=3.25,setpts=PTS-STARTPTS[$3x0];[$3a2]trim=start=3.25,setpts=(PTS-STARTPTS)/3[$3x1];[$2:v]split[$3b1][$3b2];[$3b1]trim=end=0.25,setpts=(PTS-STARTPTS)/2[$3x2];[$3b2]trim=start=0.25,setpts=PTS-STARTPTS[$3x3];[$3x0][$3x1][$3x2][$3x3]concat=n=4:v=1:a=0,fps=24,trim=duration=$part,setpts=PTS-STARTPTS,split[$3s1][$3s2];[$3s1]$card[$3v];[$3s2]$blur[$3g];"
}
ffmpeg -hide_banner -loglevel error -y -i woman_a.mp4 -i woman_b.mp4 -i man_a.mp4 -i man_b.mp4 \
-loop 1 -framerate 24 -i title_woman.png -loop 1 -framerate 24 -i title_man.png -loop 1 -framerate 24 -i mask.png \
-loop 1 -framerate 24 -i outro.png -loop 1 -framerate 24 -i frame.png -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 -filter_complex "\
$(join 0 1 w)$(join 2 3 m)\
[6:v]format=rgba,alphaextract,split[k1][k2];[wv][k1]alphamerge[wr];[mv][k2]alphamerge[mr];\
[4:v]trim=duration=$part,format=rgba[wb];[5:v]trim=duration=$part,format=rgba[mb];\
[8:v]trim=duration=$part,format=rgba,split[fw][fm];\
[wg][fw]overlay=0:0[wbg];[wbg][wr]overlay=132:240[wf];[wf][wb]overlay=0:0,format=yuv420p,setpts=PTS-STARTPTS[a];\
[mg][fm]overlay=0:0[mbg];[mbg][mr]overlay=132:240[mf];[mf][mb]overlay=0:0,format=yuv420p,setpts=PTS-STARTPTS[b];\
[7:v]trim=duration=$outro,format=yuv420p,setpts=PTS-STARTPTS[c];\
[a][b]xfade=transition=fade:duration=$fade:offset=$o1[ab];[ab][c]xfade=transition=fade:duration=$fade:offset=$o2,format=yuv420p[out]" \
-map "[out]" -map 9:a -t 15 -r 24 -c:v libx264 -preset slow -crf 18 -profile:v high -pix_fmt yuv420p \
-c:a aac -b:a 128k -ar 44100 -movflags +faststart base.mp4
# 자막: 0.2초 페이드 + 살짝 올라오며 등장
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))")
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
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
fi
if [ -n "$MUSIC" ]; then
ffmpeg -hide_banner -loglevel error -y -i bubbles.mp4 -i "$MUSIC" -filter_complex \
"[1:a]atrim=start=0.3:end=15.3,asetpts=PTS-STARTPTS,afade=t=in:st=0:d=0.2,afade=t=out:st=14.0:d=1.0,loudnorm=I=-14:TP=-1.5:LRA=11,aresample=44100[a]" \
-map 0:v -map "[a]" -c:v copy -c:a aac -b:a 192k -ar 44100 -ac 2 -t 15 -movflags +faststart final.mp4
else
mv bubbles.mp4 final.mp4
fi
rm -f base.mp4 bubbles.mp4
ffprobe -v error -show_entries format=duration:stream=codec_name,width,height -of compact final.mp4
+208
View File
@@ -0,0 +1,208 @@
"""사진 한 장으로 LTX 춤 영상을 만든다. 전용 컨테이너(server.sh)에 SSH 터널로 그래프를 보낸다.
menusong 그래프(ltx_graph.json)와 달리 고화질 단계에서도 원본 사진을 첫 프레임에 다시 고정한다.
usage: python3 generate.py --image first.png --prompt-file prompt.txt --output clip.mp4 [--duration 6 --width 1088 --height 1920]
"""
import argparse
import json
import math
import os
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
HERE = Path(__file__).resolve().parent
DEFAULT_NEGATIVE = "distorted anatomy, extra limbs, flicker, blurry, watermark, text"
UNUSED_NODES = ("409", "405:380", "405:381", "405:382", "405:383", "405:393")
def call(method, url, body=None, headers=None, timeout=60):
request = urllib.request.Request(url, data=body, method=method, headers=headers or {})
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def upload_image(base, path):
boundary = uuid.uuid4().hex
data = Path(path).read_bytes()
body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{Path(path).name}\"\r\n"
f"Content-Type: image/png\r\n\r\n").encode() + data + f"\r\n--{boundary}--\r\n".encode()
status, raw = call("POST", base + "/upload/image", body, {"Content-Type": f"multipart/form-data; boundary={boundary}"})
if status != 200:
sys.exit(f"이미지 업로드 실패 {status}: {raw[:200]!r}")
uploaded = json.loads(raw)
return "/".join(filter(None, (uploaded.get("subfolder", ""), uploaded["name"])))
def build_graph(base, args, image_name):
graph = json.loads((HERE / "ltx_graph.json").read_text(encoding="utf-8"))
graph["405:376"]["inputs"]["value"] = Path(args.prompt_file).read_text(encoding="utf-8").strip()
graph["405:373"]["inputs"]["text"] = args.negative
for node in ("405:338", "405:339"):
graph[node]["inputs"]["noise_seed"] = args.seed
graph["405:361"]["inputs"]["value"] = 24
graph["405:362"]["inputs"]["value"] = math.ceil(args.duration)
graph["405:372"]["inputs"]["value"] = args.width
graph["405:360"]["inputs"]["value"] = args.height
graph["405:364"]["inputs"]["text"] = ["405:376", 0]
for unused in UNUSED_NODES:
graph.pop(unused, None)
if args.refine_sigmas:
graph["405:395"]["inputs"]["sigmas"] = args.refine_sigmas
save = graph["75"]["inputs"]
save.update({"filename_prefix": "nalssigak/ootd", "format": "mp4", "codec": "h264",
"format.codec": "h264", "format.codec.encoding": "auto", "codec.encoding": "auto"})
status, raw = call("GET", base + "/object_info/SaveVideo")
allowed = json.loads(raw)["SaveVideo"]["input"]["required"] if status == 200 else {}
for field in ("format", "codec"):
choices = allowed.get(field, [None])[0]
if isinstance(choices, list) and save[field] not in choices:
save[field] = "auto"
# 저해상도 단계: menusong과 같은 방식으로 첫 프레임 가이드를 붙였다가 업스케일 전에 떼어낸다.
graph["_img_load"] = {"class_type": "LoadImage", "inputs": {"image": image_name}}
graph["_img_guide"] = {"class_type": "LTXVAddGuide", "inputs": {
"positive": ["405:365", 0], "negative": ["405:365", 1], "vae": ["405:385", 0],
"latent": ["405:356", 0], "image": ["_img_load", 0], "frame_idx": 0, "strength": 1.0}}
# 처음 말고도 가운데·마지막 프레임을 원본 사진으로 잡아 움직이는 동안 얼굴이 멀어지는 것을 막는다.
frames = 24 * math.ceil(args.duration)
anchors = [round(frames * k / (args.anchor_mid + 1) / 8) * 8 for k in range(1, args.anchor_mid + 1)]
if args.anchor_end:
anchors.append(-1)
def chain(prefix, source, latent):
for number, frame in enumerate(anchors):
name = f"{prefix}{number}"
graph[name] = {"class_type": "LTXVAddGuide", "inputs": {
"positive": [source, 0], "negative": [source, 1], "vae": ["405:385", 0], "latent": latent,
"image": ["_img_load", 0], "frame_idx": frame, "strength": args.end_strength}}
source, latent = name, [name, 2]
return source, latent
low, low_latent = chain("_img_anchor", "_img_guide", ["_img_guide", 2])
graph["405:377"]["inputs"]["video_latent"] = low_latent
graph["405:388"]["inputs"].update(positive=[low, 0], negative=[low, 1])
graph["_crop_guides"] = {"class_type": "LTXVCropGuides", "inputs": {
"positive": [low, 0], "negative": [low, 1], "latent": ["405:367", 0]}}
graph["405:348"]["inputs"]["samples"] = ["_crop_guides", 2]
graph["405:391"]["inputs"].update(positive=["_crop_guides", 0], negative=["_crop_guides", 1])
# 고화질 단계: 업스케일한 latent의 첫 프레임을 원본 사진으로 다시 고정한다.
graph["_hd_inplace"] = {"class_type": "LTXVImgToVideoInplace", "inputs": {
"vae": ["405:385", 0], "image": ["_img_load", 0], "latent": ["405:348", 0],
"strength": args.hd_strength, "bypass": False}}
graph["405:340"]["inputs"]["video_latent"] = ["_hd_inplace", 0]
if anchors:
high, high_latent = chain("_hd_anchor", "_crop_guides", ["_hd_inplace", 0])
graph["405:340"]["inputs"]["video_latent"] = high_latent
graph["405:391"]["inputs"].update(positive=[high, 0], negative=[high, 1])
graph["_hd_crop"] = {"class_type": "LTXVCropGuides", "inputs": {
"positive": [high, 0], "negative": [high, 1], "latent": ["405:369", 0]}}
graph["405:374"]["inputs"]["samples"] = ["_hd_crop", 2]
return graph
def wait_result(base, prompt_id, timeout):
deadline = time.monotonic() + timeout
started = time.monotonic()
while time.monotonic() < deadline:
status, raw = call("GET", base + "/history/" + prompt_id)
entry = json.loads(raw).get(prompt_id) if status == 200 else None
if entry:
state = entry.get("status", {})
if state.get("status_str") == "error":
sys.exit("생성 실패: " + json.dumps(state.get("messages", []), ensure_ascii=False)[:2000])
for items in entry.get("outputs", {}).get("75", {}).values():
for item in items if isinstance(items, list) else []:
if isinstance(item, dict) and str(item.get("filename", "")).endswith(".mp4"):
print(f"생성 완료 {time.monotonic() - started:.0f}s", flush=True)
return item
if state.get("completed"):
sys.exit("완료됐지만 MP4가 없습니다")
time.sleep(5)
sys.exit("시간 초과: 서버에서 계속 생성 중일 수 있습니다. server.sh status로 확인하세요")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--image", required=True, help="첫 프레임 PNG (width×height와 같은 비율)")
parser.add_argument("--prompt-file", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--negative", default=DEFAULT_NEGATIVE)
parser.add_argument("--duration", type=int, default=6)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--width", type=int, default=1088)
parser.add_argument("--height", type=int, default=1920)
parser.add_argument("--hd-strength", type=float, default=1.0, help="고화질 단계 첫 프레임 고정 강도 0~1")
parser.add_argument("--anchor-end", action="store_true", help="마지막 프레임도 원본 사진으로 고정 (처음·끝 자세가 같아진다)")
parser.add_argument("--anchor-mid", type=int, default=0, help="중간에 원본 사진으로 고정할 프레임 수 (고르게 나눔)")
parser.add_argument("--end-strength", type=float, default=1.0, help="중간·마지막 프레임 고정 강도")
parser.add_argument("--refine-sigmas", default="", help="고화질 단계 sigma 목록. 비우면 menusong 기본값")
parser.add_argument("--timeout", type=int, default=1800)
parser.add_argument("--keep-running", action="store_true", help="끝난 뒤 컨테이너를 내리지 않는다")
args = parser.parse_args()
for side in (args.width, args.height):
if side % 64 or not 256 <= side <= 2048:
sys.exit("width와 height는 256~2048 사이 64의 배수여야 합니다")
server = [str(HERE / "server.sh")]
if subprocess.run(server + ["up"]).returncode != 0:
sys.exit("전용 컨테이너를 시작하지 못했습니다")
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
remote_port = int(os.environ.get("OOTD_SERVER_PORT", "32681"))
host = os.environ.get("OOTD_SERVER_HOST", "King_admin")
tunnel = subprocess.Popen(["ssh", "-N", "-T", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes",
"-o", "ServerAliveInterval=15", "-L", f"127.0.0.1:{port}:127.0.0.1:{remote_port}", host],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
base = f"http://127.0.0.1:{port}"
finished = False
try:
for _ in range(100):
try:
if call("GET", base + "/system_stats", timeout=2)[0] == 200:
break
except OSError:
time.sleep(0.3)
else:
sys.exit("SSH 터널 연결 실패")
graph = build_graph(base, args, upload_image(base, args.image))
Path(args.output).with_suffix(".workflow.json").write_text(json.dumps(graph, ensure_ascii=False, indent=1), encoding="utf-8")
status, raw = call("POST", base + "/prompt", json.dumps({"prompt": graph, "client_id": uuid.uuid4().hex}).encode(),
{"Content-Type": "application/json"})
if status != 200:
sys.exit(f"그래프 제출 실패 {status}: {raw[:1500].decode(errors='replace')}")
prompt_id = json.loads(raw)["prompt_id"]
print("prompt", prompt_id, flush=True)
item = wait_result(base, prompt_id, args.timeout)
query = urllib.parse.urlencode({k: item[k] for k in ("filename", "subfolder", "type") if k in item})
status, data = call("GET", base + "/view?" + query, timeout=300)
if status != 200 or not data:
sys.exit(f"결과 다운로드 실패 {status}")
Path(args.output).write_bytes(data)
print("saved", args.output, flush=True)
finished = True
finally:
tunnel.terminate()
tunnel.wait(timeout=5)
# 실패·중단 때도 GPU를 놓아주도록 컨테이너를 멈춘다.
if not args.keep_running:
subprocess.run(server + ["down"])
if not finished:
print("중단됨: 결과를 받지 못했습니다", file=sys.stderr)
if __name__ == "__main__":
main()
+641
View File
@@ -0,0 +1,641 @@
{
"75": {
"inputs": {
"filename_prefix": "menusong/clip",
"format": "auto",
"format.codec": "auto",
"codec": "auto",
"video": [
"405:370",
0
]
},
"class_type": "SaveVideo",
"_meta": {
"title": "비디오 저장"
}
},
"409": {
"inputs": {
"aspect_ratio": "16:9 (Widescreen)",
"megapixels": 0.9,
"multiple": 32
},
"class_type": "ResolutionSelector",
"_meta": {
"title": "해상도 선택기"
}
},
"405:370": {
"inputs": {
"fps": [
"405:359",
0
],
"bit_depth": 8,
"images": [
"405:374",
0
],
"audio": [
"405:358",
0
]
},
"class_type": "CreateVideo",
"_meta": {
"title": "비디오 생성"
}
},
"405:340": {
"inputs": {
"video_latent": [
"405:348",
0
],
"audio_latent": [
"405:367",
1
]
},
"class_type": "LTXVConcatAVLatent",
"_meta": {
"title": "LTXVConcatAVLatent"
}
},
"405:395": {
"inputs": {
"sigmas": "0.85, 0.7250, 0.4219, 0.0"
},
"class_type": "ManualSigmas",
"_meta": {
"title": "ManualSigmas"
}
},
"405:348": {
"inputs": {
"samples": [
"405:367",
0
],
"upscale_model": [
"405:371",
0
],
"vae": [
"405:385",
0
]
},
"class_type": "LTXVLatentUpsampler",
"_meta": {
"title": "LTXVLatentUpsampler"
}
},
"405:358": {
"inputs": {
"samples": [
"405:369",
1
],
"audio_vae": [
"405:386",
0
]
},
"class_type": "LTXVAudioVAEDecode",
"_meta": {
"title": "LTXV 오디오 VAE 디코드"
}
},
"405:341": {
"inputs": {
"sampler_name": "euler_ancestral"
},
"class_type": "KSamplerSelect",
"_meta": {
"title": "KSampler (선택)"
}
},
"405:391": {
"inputs": {
"video_cfg": 1.0,
"audio_cfg": 1.0,
"model": [
"405:384",
0
],
"positive": [
"405:365",
0
],
"negative": [
"405:365",
1
]
},
"class_type": "LTXVDualCFGGuider",
"_meta": {
"title": "LTXV Dual CFG Guider"
}
},
"405:368": {
"inputs": {
"noise": [
"405:338",
0
],
"guider": [
"405:391",
0
],
"sampler": [
"405:341",
0
],
"sigmas": [
"405:395",
0
],
"latent_image": [
"405:340",
0
]
},
"class_type": "SamplerCustomAdvanced",
"_meta": {
"title": "고급 사용자 정의 샘플러"
}
},
"405:338": {
"inputs": {
"noise_seed": 42
},
"class_type": "RandomNoise",
"_meta": {
"title": "무작위 노이즈"
}
},
"405:367": {
"inputs": {
"av_latent": [
"405:344",
0
]
},
"class_type": "LTXVSeparateAVLatent",
"_meta": {
"title": "LTXVSeparateAVLatent"
}
},
"405:369": {
"inputs": {
"av_latent": [
"405:368",
0
]
},
"class_type": "LTXVSeparateAVLatent",
"_meta": {
"title": "LTXVSeparateAVLatent"
}
},
"405:374": {
"inputs": {
"tile_size": 512,
"overlap": 64,
"temporal_size": 64,
"temporal_overlap": 16,
"samples": [
"405:369",
0
],
"vae": [
"405:385",
0
]
},
"class_type": "VAEDecodeTiled",
"_meta": {
"title": "VAE 디코드 (타일)"
}
},
"405:344": {
"inputs": {
"noise": [
"405:339",
0
],
"guider": [
"405:388",
0
],
"sampler": [
"405:352",
0
],
"sigmas": [
"405:404",
0
],
"latent_image": [
"405:377",
0
]
},
"class_type": "SamplerCustomAdvanced",
"_meta": {
"title": "고급 사용자 정의 샘플러"
}
},
"405:404": {
"inputs": {
"sigmas": "1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875, 0.0"
},
"class_type": "ManualSigmas",
"_meta": {
"title": "ManualSigmas"
}
},
"405:388": {
"inputs": {
"video_cfg": 1.0,
"audio_cfg": 1.0,
"model": [
"405:384",
0
],
"positive": [
"405:365",
0
],
"negative": [
"405:365",
1
]
},
"class_type": "LTXVDualCFGGuider",
"_meta": {
"title": "LTXV Dual CFG Guider"
}
},
"405:352": {
"inputs": {
"sampler_name": "euler_ancestral"
},
"class_type": "KSamplerSelect",
"_meta": {
"title": "KSampler (선택)"
}
},
"405:339": {
"inputs": {
"noise_seed": 903463531924076
},
"class_type": "RandomNoise",
"_meta": {
"title": "무작위 노이즈"
}
},
"405:365": {
"inputs": {
"frame_rate": [
"405:359",
0
],
"positive": [
"405:364",
0
],
"negative": [
"405:373",
0
]
},
"class_type": "LTXVConditioning",
"_meta": {
"title": "LTXV 조건 설정"
}
},
"405:377": {
"inputs": {
"video_latent": [
"405:356",
0
],
"audio_latent": [
"405:366",
0
]
},
"class_type": "LTXVConcatAVLatent",
"_meta": {
"title": "LTXVConcatAVLatent"
}
},
"405:373": {
"inputs": {
"text": "distorted anatomy, extra limbs, flicker, blurry, watermark, text",
"clip": [
"405:387",
0
]
},
"class_type": "CLIPTextEncode",
"_meta": {
"title": "CLIP 텍스트 인코딩 (프롬프트)"
}
},
"405:356": {
"inputs": {
"width": [
"405:353",
1
],
"height": [
"405:355",
1
],
"length": [
"405:378",
1
],
"batch_size": 1
},
"class_type": "EmptyLTXVLatentVideo",
"_meta": {
"title": "빈 잠재 비디오 (LTXV)"
}
},
"405:366": {
"inputs": {
"frames_number": [
"405:378",
1
],
"frame_rate": [
"405:359",
1
],
"batch_size": 1,
"audio_vae": [
"405:386",
0
]
},
"class_type": "LTXVEmptyLatentAudio",
"_meta": {
"title": "LTXV 빈 latent 오디오"
}
},
"405:381": {
"inputs": {
"source": [
"405:382",
0
]
},
"class_type": "PreviewAny",
"_meta": {
"title": "미리보기 아무거나"
}
},
"405:382": {
"inputs": {
"switch": [
"405:383",
0
],
"on_false": [
"405:376",
0
],
"on_true": [
"405:380",
0
]
},
"class_type": "ComfySwitchNode",
"_meta": {
"title": "스위치"
}
},
"405:371": {
"inputs": {
"model_name": "ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors"
},
"class_type": "LatentUpscaleModelLoader",
"_meta": {
"title": "Latent 업스케일 모델 불러오기"
}
},
"405:384": {
"inputs": {
"unet_name": "ltx-2.5-22b-distilled-transformer-comfy-int8-convrot.safetensors",
"weight_dtype": "default"
},
"class_type": "UNETLoader",
"_meta": {
"title": "확산 모델 로드"
}
},
"405:385": {
"inputs": {
"vae_name": "ltx-2.5-video-vae-bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": {
"title": "VAE 로드"
}
},
"405:386": {
"inputs": {
"vae_name": "ltx-2.5-audio-vae-bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": {
"title": "VAE 로드"
}
},
"405:387": {
"inputs": {
"clip_name": "gemma4-12b-with-proj-ltx-2.5-comfy-int8-convrot.safetensors",
"type": "ltxv",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": {
"title": "CLIP 로드"
}
},
"405:380": {
"inputs": {
"prompt": [
"405:376",
0
],
"max_length": 600,
"sampling_mode": "on",
"sampling_mode.temperature": 0.7,
"sampling_mode.top_k": 64,
"sampling_mode.top_p": 0.95,
"sampling_mode.min_p": 0.05,
"sampling_mode.repetition_penalty": 1.15,
"sampling_mode.seed": 0,
"sampling_mode.presence_penalty": 0.0,
"thinking": false,
"use_default_template": true,
"clip": [
"405:393",
0
]
},
"class_type": "TextGenerateLTX2Prompt",
"_meta": {
"title": "TextGenerateLTX2Prompt"
}
},
"405:378": {
"inputs": {
"expression": "a * b + 1",
"values.a": [
"405:362",
0
],
"values.b": [
"405:361",
0
]
},
"class_type": "ComfyMathExpression",
"_meta": {
"title": "Math Expression (length)"
}
},
"405:353": {
"inputs": {
"expression": "a/2",
"values.a": [
"405:372",
0
]
},
"class_type": "ComfyMathExpression",
"_meta": {
"title": "수학식"
}
},
"405:355": {
"inputs": {
"expression": "a/2",
"values.a": [
"405:360",
0
]
},
"class_type": "ComfyMathExpression",
"_meta": {
"title": "수학식"
}
},
"405:359": {
"inputs": {
"expression": "a",
"values.a": [
"405:361",
0
]
},
"class_type": "ComfyMathExpression",
"_meta": {
"title": "Math Expression (fps)"
}
},
"405:360": {
"inputs": {
"value": [
"409",
1
]
},
"class_type": "PrimitiveInt",
"_meta": {
"title": "Height"
}
},
"405:361": {
"inputs": {
"value": 24
},
"class_type": "PrimitiveInt",
"_meta": {
"title": "Frame Rate"
}
},
"405:362": {
"inputs": {
"value": 5
},
"class_type": "PrimitiveInt",
"_meta": {
"title": "Duration"
}
},
"405:372": {
"inputs": {
"value": [
"409",
0
]
},
"class_type": "PrimitiveInt",
"_meta": {
"title": "Width"
}
},
"405:376": {
"inputs": {
"value": "A single cute rounded rice-cake mascot waves hello on a colorful stage, gentle toy-like 3D animation, warm soft lighting, stable camera."
},
"class_type": "PrimitiveStringMultiline",
"_meta": {
"title": "Prompt"
}
},
"405:393": {
"inputs": {
"clip_name": "gemma4-12b-with-proj-ltx-2.5-comfy-int8-convrot.safetensors",
"type": "ltxv",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": {
"title": "CLIP 로드"
}
},
"405:383": {
"inputs": {
"value": false
},
"class_type": "PrimitiveBoolean",
"_meta": {
"title": "Boolean (Enable Prompt Enhance)"
}
},
"405:364": {
"inputs": {
"text": [
"405:382",
0
],
"clip": [
"405:387",
0
]
},
"class_type": "CLIPTextEncode",
"_meta": {
"title": "CLIP 텍스트 인코딩 (프롬프트)"
}
}
}
+76
View File
@@ -0,0 +1,76 @@
"""templates/ 의 HTML을 헤드리스 크롬으로 PNG로 찍는다.
usage:
python3 render.py title --age 30 --who 여성 --label 하객룩 --out title_woman.png
python3 render.py bubble --text "*크롭 재킷*으로 시크하게" --out bubbles/w1.png
python3 render.py frame --out frame.png
python3 render.py outro --out outro.png
python3 render.py mask --out mask.png
자막: *단어* 는 주황 강조, | 는 띄어쓰기로 바뀐다(한 줄). title·bubble 은 영상 위에 얹는 투명 PNG, frame 은 흐린 배경과 영상 사이의 창 그림자.
"""
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
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")
# compose.sh 의 영상 창 크기와 같아야 한다
CARD = (816, 1440)
def shoot(url, out, size=(1080, 1920), transparent=False):
profile = tempfile.mkdtemp(prefix="render-")
command = [CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", f"--user-data-dir={profile}",
"--force-device-scale-factor=1", f"--window-size={size[0]},{size[1]}", "--virtual-time-budget=6000",
f"--screenshot={Path(out).resolve()}", url]
if transparent:
command.insert(-1, "--default-background-color=00000000")
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).unlink(missing_ok=True)
try:
# 크롬이 가끔 멈추므로 40초에서 끊는다
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=40)
except subprocess.TimeoutExpired:
pass
finally:
shutil.rmtree(profile, ignore_errors=True)
if not Path(out).is_file():
sys.exit(f"찍지 못했어요: {out}")
print("saved", out)
def page(name, **query):
return (TEMPLATES / name).as_uri() + ("?" + urllib.parse.urlencode(query) if query else "")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("kind", choices=["title", "bubble", "frame", "outro", "mask"])
parser.add_argument("--out", required=True)
parser.add_argument("--age", default="20")
parser.add_argument("--who", default="여성")
parser.add_argument("--label", default="코디")
parser.add_argument("--text")
args = parser.parse_args()
if args.kind == "title":
shoot(page("title.html", age=args.age, who=args.who, label=args.label), args.out, transparent=True)
elif args.kind == "bubble":
if args.text is None:
sys.exit("bubble 은 --text 가 필요해요")
shoot(page("bubble.html", t=args.text), args.out, transparent=True)
elif args.kind == "frame":
shoot(page("frame.html"), args.out, transparent=True)
elif args.kind == "outro":
shoot(page("outro.html"), args.out)
else:
html = f"<body style='margin:0;background:transparent'><div style='width:{CARD[0]}px;height:{CARD[1]}px;border-radius:40px;background:white'></div></body>"
shoot("data:text/html," + urllib.parse.quote(html), args.out, size=CARD, transparent=True)
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
#!/bin/bash
# King_admin에 날씨각 코디 영상 전용 ComfyUI(LTX) 컨테이너를 띄우고 내린다. menusong 서비스·파일은 건드리지 않는다.
# usage: server.sh up | down | status | remove
set -euo pipefail
HOST=${OOTD_SERVER_HOST:-King_admin}
PORT=${OOTD_SERVER_PORT:-32681}
NAME=nalssigak-ltx
ROOT=/mnt/data2/nalssigak
MODELS=/mnt/data2/dir/jw_playground/LTX-2.5
IMAGE=jw/comfyui-ltx:latest
GPU=${OOTD_GPU:-0}
remote() { ssh -o BatchMode=yes -o ConnectTimeout=15 "$HOST" "$@"; }
up() {
remote "NAME=$NAME ROOT=$ROOT MODELS=$MODELS IMAGE=$IMAGE GPU=$GPU PORT=$PORT bash -s" <<'EOF'
set -euo pipefail
running() { docker inspect -f '{{.State.Running}}' "$1" 2>/dev/null | tr -d '[:space:]' || true; }
state=$(running "$NAME"); state=${state:-missing}
if [ "$state" != true ]; then
# menusong은 GPU 0에 qwen·image·tts, GPU 1에 video·music을 띄운다.
if [ "$GPU" = 0 ]; then busy="menusong-qwen menusong-image menusong-tts"; else busy="menusong-video menusong-music"; fi
for other in $busy; do
if [ "$(running "$other")" = true ]; then
echo "$other 가 GPU $GPU 를 쓰는 중이라 시작하지 않습니다. 끝난 뒤 다시 실행하세요." >&2; exit 3
fi
done
used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$GPU" | tr -d ' ')
if [ "$used" -gt 2000 ]; then
echo "GPU $GPU 사용 중(${used}MiB)이라 시작하지 않습니다." >&2; exit 3
fi
# 멈춘 컨테이너는 GPU 설정이 다를 수 있어 새로 만든다.
docker rm "$NAME" >/dev/null 2>&1 || true
mkdir -p "$ROOT"/comfy/{input,output,temp,user}
docker run -d --name "$NAME" --init --gpus "device=$GPU" --shm-size 2g \
-p "127.0.0.1:$PORT:8188" --label nalssigak.ootd=true \
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 -e PYTHONUNBUFFERED=1 \
-v "$MODELS/vae:/app/models/vae:ro" -v "$MODELS/model_patches:/app/models/model_patches:ro" \
-v "$MODELS/latent_upscale_models:/app/models/latent_upscale_models:ro" \
-v "$MODELS/diffusion_models:/app/models/diffusion_models:ro" -v "$MODELS/text_encoders:/app/models/text_encoders:ro" \
-v "$ROOT/comfy/input:/app/input" -v "$ROOT/comfy/output:/app/output" \
-v "$ROOT/comfy/temp:/app/temp" -v "$ROOT/comfy/user:/app/user" \
--entrypoint python "$IMAGE" main.py --listen 0.0.0.0 --port 8188 --lowvram >/dev/null
fi
for _ in $(seq 1 150); do
curl -sf "http://127.0.0.1:$PORT/system_stats" >/dev/null && { echo ready; exit 0; }
[ "$(running "$NAME")" = true ] || { docker logs --tail 30 "$NAME" >&2; exit 1; }
sleep 2
done
echo "$NAME 이(가) 5분 안에 준비되지 않았습니다." >&2; exit 1
EOF
}
# 결과는 PC로 내려받았으므로 끌 때 서버의 입력·결과 파일을 지운다 (컨테이너가 root로 써서 같은 이미지로 지운다).
down() {
remote "docker stop -t 30 $NAME >/dev/null 2>&1 && echo stopped || echo 'not running'; \
[ -d $ROOT/comfy ] && docker run --rm -v $ROOT/comfy:/c --entrypoint sh $IMAGE -c 'rm -rf /c/input/* /c/output/* /c/temp/*' || true"
}
status() {
remote "docker ps -a --filter name=^/$NAME\$ --format '{{.Names}} {{.Status}}'; \
nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader -i $GPU; du -sh $ROOT 2>/dev/null || true"
}
remove() {
# 컨테이너가 root로 쓴 파일이 있어 같은 이미지로 지운다.
remote "docker rm -f $NAME nalssigak-music >/dev/null 2>&1 || true; \
if [ -d $ROOT ]; then docker run --rm -v $ROOT:/target --entrypoint sh $IMAGE -c 'rm -rf /target/* /target/.[!.]*' && rmdir $ROOT; fi; \
echo removed"
}
case "${1:-}" in
up) up ;;
down) down ;;
status) status ;;
remove) remove ;;
*) echo "usage: $0 up|down|status|remove" >&2; exit 2 ;;
esac
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
# usage: sheet.sh <영상> <출력.png> <초> [초 ...] — 그 시각 프레임을 가로로 붙인 확인용 시트
set -euo pipefail
video=$1; out=$2; shift 2
tmp=$(mktemp -d); inputs=(); n=0
for t in "$@"; do ffmpeg -hide_banner -loglevel error -y -ss "$t" -i "$video" -frames:v 1 -vf scale=270:480 "$tmp/$n.png"; inputs+=(-i "$tmp/$n.png"); n=$((n+1)); done
ffmpeg -hide_banner -loglevel error -y "${inputs[@]}" -filter_complex "hstack=inputs=$n" "$out"
rm -rf "$tmp"; echo "saved $out"
+140
View File
@@ -0,0 +1,140 @@
"""YouTube Shorts 업로드. 표준 라이브러리만 쓴다 (OAuth 데스크톱 앱 + resumable upload).
usage:
python3 youtube.py auth # 채널 계정으로 한 번 로그인해 refresh token을 저장
python3 youtube.py upload video.mp4 meta.json # meta: {title, description, tags[], privacy}
비밀 파일은 저장소 밖 ~/.config/nalssigak/ 에 둔다 (client_secret.json, youtube_token.json).
감사를 통과해 공개로 올릴 수 있게 되면 ~/.config/nalssigak/youtube_public 파일을 만든다(스킬이 privacy 를 public 으로 쓴다).
"""
import base64
import hashlib
import http.server
import json
import os
import secrets
import socket
import sys
import threading
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from pathlib import Path
CONFIG = Path(os.environ.get("NALSSIGAK_CONFIG", Path.home() / ".config" / "nalssigak"))
CLIENT = CONFIG / "client_secret.json"
TOKEN = CONFIG / "youtube_token.json"
SCOPE = "https://www.googleapis.com/auth/youtube.upload"
TOKEN_URL = "https://oauth2.googleapis.com/token"
def client():
data = json.loads(CLIENT.read_text(encoding="utf-8"))
return data.get("installed") or data["web"]
def post_form(url, fields):
body = urllib.parse.urlencode(fields).encode()
request = urllib.request.Request(url, data=body, headers={"Content-Type": "application/x-www-form-urlencoded"})
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.loads(response.read())
except urllib.error.HTTPError as error:
sys.exit(f"토큰 요청 실패 {error.code}: {error.read()[:300].decode(errors='replace')}")
def auth():
c = client()
verifier = secrets.token_urlsafe(64)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(16)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
redirect = f"http://127.0.0.1:{port}"
result = {}
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
if query.get("state", [""])[0] == state:
result.update({k: v[0] for k, v in query.items()})
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write("로그인 완료. 이 창은 닫아도 돼요.".encode())
def log_message(self, *_):
pass
server = http.server.HTTPServer(("127.0.0.1", port), Handler)
url = c["auth_uri"] + "?" + urllib.parse.urlencode({
"client_id": c["client_id"], "redirect_uri": redirect, "response_type": "code", "scope": SCOPE,
"access_type": "offline", "prompt": "consent", "state": state,
"code_challenge": challenge, "code_challenge_method": "S256"})
print("브라우저에서 채널 계정으로 로그인하세요:\n" + url, flush=True)
webbrowser.open(url)
thread = threading.Thread(target=server.handle_request)
thread.start()
thread.join(timeout=600)
server.server_close()
if "code" not in result:
sys.exit(f"로그인이 끝나지 않았어요: {result.get('error', '시간 초과')}")
token = post_form(c["token_uri"], {"client_id": c["client_id"], "client_secret": c["client_secret"], "code": result["code"],
"code_verifier": verifier, "grant_type": "authorization_code", "redirect_uri": redirect})
if "refresh_token" not in token:
sys.exit("refresh token을 받지 못했어요. 다시 auth를 실행하세요.")
CONFIG.mkdir(parents=True, exist_ok=True)
TOKEN.write_text(json.dumps({"refresh_token": token["refresh_token"], "scope": token.get("scope")}), encoding="utf-8")
TOKEN.chmod(0o600)
print("저장했어요:", TOKEN)
def access_token():
if not TOKEN.is_file():
sys.exit("먼저 python3 youtube.py auth 로 로그인하세요.")
c = client()
refresh = json.loads(TOKEN.read_text(encoding="utf-8"))["refresh_token"]
return post_form(TOKEN_URL, {"client_id": c["client_id"], "client_secret": c["client_secret"],
"refresh_token": refresh, "grant_type": "refresh_token"})["access_token"]
def upload(video_path, meta_path):
meta = json.loads(Path(meta_path).read_text(encoding="utf-8"))
video = Path(video_path).read_bytes()
body = {
"snippet": {"title": meta["title"], "description": meta["description"], "tags": meta.get("tags", []),
"categoryId": meta.get("category", "26"), "defaultLanguage": "ko", "defaultAudioLanguage": "ko"},
"status": {"privacyStatus": meta.get("privacy", "private"), "selfDeclaredMadeForKids": False,
"containsSyntheticMedia": True},
}
token = access_token()
start = urllib.request.Request(
"https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status",
data=json.dumps(body).encode(), method="POST",
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": "video/mp4", "X-Upload-Content-Length": str(len(video))})
try:
with urllib.request.urlopen(start, timeout=60) as response:
location = response.headers["Location"]
put = urllib.request.Request(location, data=video, method="PUT",
headers={"Authorization": f"Bearer {token}", "Content-Type": "video/mp4"})
with urllib.request.urlopen(put, timeout=600) as response:
result = json.loads(response.read())
except urllib.error.HTTPError as error:
sys.exit(f"업로드 실패 {error.code}: {error.read()[:600].decode(errors='replace')}")
asked, got = body["status"]["privacyStatus"], result["status"]["privacyStatus"]
print(json.dumps({"id": result["id"], "privacy": got, "url": f"https://youtube.com/shorts/{result['id']}",
"studio": f"https://studio.youtube.com/video/{result['id']}/edit"}, ensure_ascii=False))
if asked != got:
# 감사 전 API 프로젝트는 공개 요청도 비공개로 바뀐다
print(f"경고: {asked} 로 요청했지만 {got} 로 올라갔어요. API 감사가 필요해요.", file=sys.stderr)
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "auth":
auth()
elif len(sys.argv) == 4 and sys.argv[1] == "upload":
upload(sys.argv[2], sys.argv[3])
else:
sys.exit(__doc__)
+21
View File
@@ -0,0 +1,21 @@
{
"about": "클립 동작 후보. scripts/actions.py 가 사람마다 겹치지 않게 무작위로 고른다. 손가락 모양(하트·V·OK·엄지)은 영상 모델이 다른 손 모양으로 그려서 넣지 않는다. needs 는 그 옷·가방이 있어야 쓸 수 있는 동작",
"woman": [
{ "text": "She smiles brightly and gives a cute little wave to the camera with her free hand at shoulder height, then lowers her hand back to her starting pose." },
{ "text": "She smiles and slowly tucks a strand of hair behind her ear with her free hand without looking away from the camera, then lowers her hand back to her starting pose." },
{ "text": "She smiles and lightly brushes her hair back from her face with her free hand, keeping her whole face visible, then lowers her hand back to her starting pose." },
{ "text": "She smiles and with her free hand gently draws the front of her open outer layer a little closed at chest height without looking down, then lets go and lowers her hand back to her starting pose.", "needs": ["outer"] },
{ "text": "She smiles and lifts her free hand to lightly touch the collar of her outer layer near her neck, then lowers her hand back to her starting pose.", "needs": ["outer"] },
{ "text": "She smiles and with her free hand lightly adjusts the strap of her bag on her shoulder without looking at it, then lowers her hand back to her starting pose.", "needs": ["bag"] },
{ "text": "She smiles and shifts her weight gently onto one leg with a small relaxed shoulder shrug, then settles back into her starting pose." }
],
"man": [
{ "text": "He smiles and gives a friendly small wave to the camera with his free hand at shoulder height, then lowers his hand back to his starting pose." },
{ "text": "He gives a slight confident smile and with his free hand at waist level lightly tugs the bottom front edge of his outer layer once to straighten it without looking at it, then lowers his hand back to his starting pose.", "needs": ["outer"] },
{ "text": "He gives a slight confident smile and with his free hand straightens the collar of his outer layer near his neck without looking down, then lowers his hand back to his starting pose.", "needs": ["outer"] },
{ "text": "He gives a slight confident smile and slowly runs his free hand through the side of his hair, keeping his whole face visible, then lowers his hand back to his starting pose." },
{ "text": "He gives a slight confident smile and with his free hand slowly adjusts the cuff of his other sleeve at waist height without looking at it, then lowers his hand back to his starting pose." },
{ "text": "He gives a slight confident smile and with his free hand lightly adjusts the strap of his bag on his shoulder without looking at it, then lowers his hand back to his starting pose.", "needs": ["bag"] },
{ "text": "He gives a relaxed half-smile and slides his free hand into his trouser pocket in one easy motion, keeping it there until the end." }
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+15
View File
@@ -0,0 +1,15 @@
<!doctype html><html lang="ko"><head><meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css">
<style>
/* 제목(title.html) 바로 아래 한 줄 자막. 창 오른쪽(948px) 안에서 끝나야 한다 */
* { margin: 0; box-sizing: border-box; }
html, body { width: 1080px; height: 1920px; background: transparent; overflow: hidden; }
.t { position: absolute; left: 176px; top: 1397px; max-width: 748px; padding: 14px 24px; border-radius: 22px; background: rgb(255 255 255 / .92);
color: #28304a; font: 600 32px/1.3 'Pretendard Variable', Pretendard, sans-serif; letter-spacing: -.5px; white-space: nowrap; }
.t em { font-style: normal; color: #d4552a; }
</style></head><body>
<div class="t" id="t"></div>
<script>
const q = new URLSearchParams(location.search);
document.getElementById('t').innerHTML = q.get('t').replace(/\*([^*]+)\*/g, '<em>$1</em>').split('|').join(' ');
</script></body></html>
+10
View File
@@ -0,0 +1,10 @@
<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<style>
/* 흐린 영상 배경 위에 얹는 투명 레이어(영상 창 그림자). 창은 프로필 그리드 3:4(위 240 ~ 아래 1680)를 채우고, 위치는 compose.sh 와 같아야 한다 */
* { margin: 0; box-sizing: border-box; }
html, body { width: 1080px; height: 1920px; overflow: hidden; }
body { position: relative; background: transparent; }
.win { position: absolute; left: 132px; top: 240px; width: 816px; height: 1440px; border-radius: 40px; background: #dfeaf6; box-shadow: 0 24px 60px rgb(20 30 60 / .35); }
</style></head>
<body><div class="win"></div></body></html>
@@ -0,0 +1 @@
A static tripod shot of {a_person} with {look} standing in {pronoun} pose in {scene}. {Pronoun} wears {outfit}. {action} A steady breeze clearly blows {pronoun} hair and makes {pronoun} clothes move lightly. {Pronoun} head stays upright facing the camera and {pronoun} eyes stay open with the same smile. The camera is completely still on a tripod at the same full-body framing, and {pronoun} face, outfit and proportions stay identical to the first frame.
+1
View File
@@ -0,0 +1 @@
falling leaves, dancing, walking, turning, big movement, camera movement, dolly in, zoom in, close-up, closed eyes, head tilt, long neck, stretched neck, different face, changing face, changing outfit, distorted anatomy, extra limbs, extra fingers, morphing, flicker, blurry, watermark, text, subtitles
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Jua&display=swap">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css">
<style>
* { margin: 0; box-sizing: border-box; }
html, body { width: 1080px; height: 1920px; overflow: hidden; }
body { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 44px; color: #1f2d3d;
font-family: 'Pretendard Variable', Pretendard, sans-serif;
background: radial-gradient(circle at 10% 4%, #dcebff 0, transparent 34%), radial-gradient(circle at 92% 97%, #d6e7fd 0, transparent 36%), #f4f9ff; }
img { width: 340px; height: 340px; border-radius: 80px; box-shadow: 0 22px 48px rgba(43, 108, 184, .25); }
.name { font: 120px/1 Jua, sans-serif; letter-spacing: -2px; }
.url { padding: 18px 44px 16px; border-radius: 999px; background: #4f97e3; color: #fff; font: 700 54px/1 'Pretendard Variable', Pretendard, sans-serif; box-shadow: 0 6px 0 #2b6cb8; }
</style></head>
<body><img src="app_icon.png" alt=""><div class="name">날씨각</div><div class="url">weather.o2o.kr</div></body></html>
@@ -0,0 +1,5 @@
Make a photo of the {person} from the first reference image wearing today's outfit in {scene}.
Outfit: {outfit}
{hair_line}
{body_line}
Rules: keep the person's face, hairstyle and body exactly like the FIRST reference image (same person). Copy the outfit items, colors, materials and silhouettes from the other reference images (outfit snap and product photos), but do NOT copy the face of the person in the outfit snap and do NOT copy any text, logo, watermark or "AI" badge. Photorealistic vertical 9:16 full-body fashion photo, the person stands facing the camera in a relaxed natural pose, whole body from head to shoes in frame with some space above the head, both hands visible and natural, eyes open, gentle expression. No text, no logo, no watermark anywhere.
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Jua&display=swap">
<style>
/* 영상 위에 얹는 투명 레이어. 창(132,240 · 816×1440) 왼쪽 아래, 신발이 보이도록 발 위(다리 높이)에 칩·제목을 두고, 그 아래 1397px 줄은 자막(bubble.html) 자리 */
:root { --main: #4f97e3; --deep: #2b6cb8; --ink: #28304a; }
* { margin: 0; box-sizing: border-box; }
html, body { width: 1080px; height: 1920px; overflow: hidden; background: transparent; }
.win { position: absolute; left: 132px; top: 240px; width: 816px; height: 1440px; border-radius: 40px; overflow: hidden; }
.shade { position: absolute; left: 0; right: 0; bottom: 0; height: 700px; background: linear-gradient(transparent, rgb(40 48 74 / .45) 55%, rgb(40 48 74 / .2)); }
.title { position: absolute; left: 176px; bottom: 543px; }
.chip { display: inline-block; padding: 9px 22px 7px; border-radius: 999px; background: var(--main); color: #fff; font: 30px/1.1 Jua, sans-serif; box-shadow: 0 4px 0 var(--deep); }
.headline { margin-top: 16px; font: 66px/1.12 Jua, sans-serif; color: #fff; letter-spacing: -1px; text-shadow: 0 3px 16px rgb(40 48 74 / .35); }
</style></head>
<body>
<div class="win"><div class="shade"></div></div>
<div class="title"><div class="chip">날씨각</div><div class="headline" id="h"></div></div>
<script>
const q = new URLSearchParams(location.search);
const age = q.get('age'); // 40~ 이면 '40대~'
document.getElementById('h').innerHTML = `이번주 ${age.replace(/~$/, '')}대${age.endsWith('~') ? '~' : ''}<br>${q.get('who')} ${q.get('label') || '코디'}`;
</script>
</body></html>