Files
o2o-weather/admin/nalssigak/scripts/generate.py
T

209 lines
11 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""사진 한 장으로 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()