feat: 이번주 코디 영상 스크립트·템플릿·모델 사진과 명령 파일 추가, 클립 동작은 후보에서 무작위로 고름 (손가락 모양 동작 제외), .sh·.py·.mjs 는 LF 로 받음
This commit is contained in:
1 parent
1ec87a82c1
commit
56f71cdfbe
54 files changed
+1576
No files matched your search
@@ -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()
|
||||
Executable
+22
@@ -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
|
||||
Executable
+55
@@ -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()
|
||||
Executable
+58
@@ -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
|
||||
Executable
+208
@@ -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()
|
||||
@@ -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 텍스트 인코딩 (프롬프트)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+76
@@ -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()
|
||||
Executable
+79
@@ -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
|
||||
Executable
+8
@@ -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"
|
||||
Executable
+140
@@ -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__)
|
||||
Reference in new issue
Block a user